blob: 161c269ef0a02eeccb7b58a5ad2aaa0a64f65880 [file] [log] [blame]
Mikhail Glushenkovc834bbf2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
Chris Lattner52f7e902001-10-13 07:03:50 +000012//===----------------------------------------------------------------------===//
13
Reid Spencer7cc371a2004-11-14 23:27:04 +000014#include "llvm/Linker.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Rafael Espindola3ed88152012-01-05 23:02:01 +000016#include "llvm/ADT/Optional.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000017#include "llvm/ADT/SetVector.h"
Eli Bendersky58890d52013-03-19 15:26:24 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/Module.h"
Chandler Carruth4068e1a2013-01-07 15:43:51 +000021#include "llvm/IR/TypeFinder.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000022#include "llvm/Support/Debug.h"
Bill Wendlingcd7193f2012-03-22 20:28:27 +000023#include "llvm/Support/raw_ostream.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000024#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner1afcace2011-07-09 17:41:24 +000027//===----------------------------------------------------------------------===//
28// TypeMap implementation.
29//===----------------------------------------------------------------------===//
Chris Lattner5c377c52001-10-14 23:29:15 +000030
Chris Lattner62a81a12008-06-16 21:00:18 +000031namespace {
Chris Lattner1afcace2011-07-09 17:41:24 +000032class TypeMapTy : public ValueMapTypeRemapper {
33 /// MappedTypes - This is a mapping from a source type to a destination type
34 /// to use.
35 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000036
Chris Lattner1afcace2011-07-09 17:41:24 +000037 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
38 /// we speculatively add types to MappedTypes, but keep track of them here in
39 /// case we need to roll back.
40 SmallVector<Type*, 16> SpeculativeTypes;
41
Chris Lattner68910502011-12-20 00:03:52 +000042 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
43 /// source module that are mapped to an opaque struct in the destination
44 /// module.
45 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
46
47 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
48 /// destination modules who are getting a body from the source module.
49 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling6d6c6d72012-03-22 20:30:41 +000050
Chris Lattnerfc196f92008-06-16 23:06:51 +000051public:
Chris Lattner1afcace2011-07-09 17:41:24 +000052 /// addTypeMapping - Indicate that the specified type in the destination
53 /// module is conceptually equivalent to the specified type in the source
54 /// module.
55 void addTypeMapping(Type *DstTy, Type *SrcTy);
56
57 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
58 /// module from a type definition in the source module.
59 void linkDefinedTypeBodies();
60
61 /// get - Return the mapped type to use for the specified input type from the
62 /// source module.
63 Type *get(Type *SrcTy);
64
65 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
66
Bill Wendlingcd7193f2012-03-22 20:28:27 +000067 /// dump - Dump out the type map for debugging purposes.
68 void dump() const {
69 for (DenseMap<Type*, Type*>::const_iterator
70 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
71 dbgs() << "TypeMap: ";
72 I->first->dump();
73 dbgs() << " => ";
74 I->second->dump();
75 dbgs() << '\n';
76 }
77 }
Bill Wendlingcd7193f2012-03-22 20:28:27 +000078
Chris Lattner1afcace2011-07-09 17:41:24 +000079private:
80 Type *getImpl(Type *T);
81 /// remapType - Implement the ValueMapTypeRemapper interface.
82 Type *remapType(Type *SrcTy) {
83 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000084 }
Chris Lattner1afcace2011-07-09 17:41:24 +000085
86 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000087};
88}
89
Chris Lattner1afcace2011-07-09 17:41:24 +000090void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
91 Type *&Entry = MappedTypes[SrcTy];
92 if (Entry) return;
93
94 if (DstTy == SrcTy) {
95 Entry = DstTy;
96 return;
97 }
Bill Wendling601c0942012-02-28 04:01:21 +000098
Chris Lattner1afcace2011-07-09 17:41:24 +000099 // Check to see if these types are recursively isomorphic and establish a
100 // mapping between them if so.
Bill Wendling601c0942012-02-28 04:01:21 +0000101 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000102 // Oops, they aren't isomorphic. Just discard this request by rolling out
103 // any speculative mappings we've established.
104 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
105 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendling601c0942012-02-28 04:01:21 +0000106 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000107 SpeculativeTypes.clear();
108}
Chris Lattner62a81a12008-06-16 21:00:18 +0000109
Chris Lattner1afcace2011-07-09 17:41:24 +0000110/// areTypesIsomorphic - Recursively walk this pair of types, returning true
111/// if they are isomorphic, false if they are not.
112bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
113 // Two types with differing kinds are clearly not isomorphic.
114 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000115
Chris Lattner1afcace2011-07-09 17:41:24 +0000116 // If we have an entry in the MappedTypes table, then we have our answer.
117 Type *&Entry = MappedTypes[SrcTy];
118 if (Entry)
119 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000120
Chris Lattner1afcace2011-07-09 17:41:24 +0000121 // Two identical types are clearly isomorphic. Remember this
122 // non-speculatively.
123 if (DstTy == SrcTy) {
124 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000125 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000126 }
Bill Wendling601c0942012-02-28 04:01:21 +0000127
Chris Lattner1afcace2011-07-09 17:41:24 +0000128 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000129
Chris Lattner1afcace2011-07-09 17:41:24 +0000130 // If this is an opaque struct type, special case it.
131 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
132 // Mapping an opaque type to any struct, just keep the dest struct.
133 if (SSTy->isOpaque()) {
134 Entry = DstTy;
135 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000136 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000137 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000138
Chris Lattner68910502011-12-20 00:03:52 +0000139 // Mapping a non-opaque source type to an opaque dest. If this is the first
140 // type that we're mapping onto this destination type then we succeed. Keep
141 // the dest, but fill it in later. This doesn't need to be speculative. If
142 // this is the second (different) type that we're trying to map onto the
143 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000144 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000145 // We can only map one source type onto the opaque destination type.
146 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
147 return false;
148 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000149 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000150 return true;
151 }
152 }
153
154 // If the number of subtypes disagree between the two types, then we fail.
155 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000156 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000157
158 // Fail if any of the extra properties (e.g. array size) of the type disagree.
159 if (isa<IntegerType>(DstTy))
160 return false; // bitwidth disagrees.
161 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
162 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
163 return false;
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000164
Chris Lattner1afcace2011-07-09 17:41:24 +0000165 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
166 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
167 return false;
168 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
169 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000170 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000171 DSTy->isPacked() != SSTy->isPacked())
172 return false;
173 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
174 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
175 return false;
176 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly2b8f6ae2013-01-10 10:49:36 +0000177 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattner1afcace2011-07-09 17:41:24 +0000178 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000179 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000180
181 // Otherwise, we speculate that these two types will line up and recursively
182 // check the subelements.
183 Entry = DstTy;
184 SpeculativeTypes.push_back(SrcTy);
185
Bill Wendling601c0942012-02-28 04:01:21 +0000186 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
187 if (!areTypesIsomorphic(DstTy->getContainedType(i),
188 SrcTy->getContainedType(i)))
Chris Lattner1afcace2011-07-09 17:41:24 +0000189 return false;
190
191 // If everything seems to have lined up, then everything is great.
192 return true;
193}
194
195/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
196/// module from a type definition in the source module.
197void TypeMapTy::linkDefinedTypeBodies() {
198 SmallVector<Type*, 16> Elements;
199 SmallString<16> TmpName;
200
201 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000202 // entries to the SrcDefinitionsToResolve vector.
203 while (!SrcDefinitionsToResolve.empty()) {
204 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000205 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
206
207 // TypeMap is a many-to-one mapping, if there were multiple types that
208 // provide a body for DstSTy then previous iterations of this loop may have
209 // already handled it. Just ignore this case.
210 if (!DstSTy->isOpaque()) continue;
211 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
212
213 // Map the body of the source type over to a new body for the dest type.
214 Elements.resize(SrcSTy->getNumElements());
215 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
216 Elements[i] = getImpl(SrcSTy->getElementType(i));
217
218 DstSTy->setBody(Elements, SrcSTy->isPacked());
219
220 // If DstSTy has no name or has a longer name than STy, then viciously steal
221 // STy's name.
222 if (!SrcSTy->hasName()) continue;
223 StringRef SrcName = SrcSTy->getName();
224
225 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
226 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
227 SrcSTy->setName("");
228 DstSTy->setName(TmpName.str());
229 TmpName.clear();
230 }
231 }
Chris Lattner68910502011-12-20 00:03:52 +0000232
233 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000234}
235
Chris Lattner1afcace2011-07-09 17:41:24 +0000236/// get - Return the mapped type to use for the specified input type from the
237/// source module.
238Type *TypeMapTy::get(Type *Ty) {
239 Type *Result = getImpl(Ty);
240
241 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner68910502011-12-20 00:03:52 +0000242 if (!SrcDefinitionsToResolve.empty())
Chris Lattner1afcace2011-07-09 17:41:24 +0000243 linkDefinedTypeBodies();
244 return Result;
245}
246
247/// getImpl - This is the recursive version of get().
248Type *TypeMapTy::getImpl(Type *Ty) {
249 // If we already have an entry for this type, return it.
250 Type **Entry = &MappedTypes[Ty];
251 if (*Entry) return *Entry;
Bill Wendling601c0942012-02-28 04:01:21 +0000252
Chris Lattner1afcace2011-07-09 17:41:24 +0000253 // If this is not a named struct type, then just map all of the elements and
254 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000255 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000256 // If there are no element types to map, then the type is itself. This is
257 // true for the anonymous {} struct, things like 'float', integers, etc.
258 if (Ty->getNumContainedTypes() == 0)
259 return *Entry = Ty;
260
261 // Remap all of the elements, keeping track of whether any of them change.
262 bool AnyChange = false;
263 SmallVector<Type*, 4> ElementTypes;
264 ElementTypes.resize(Ty->getNumContainedTypes());
265 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
266 ElementTypes[i] = getImpl(Ty->getContainedType(i));
267 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
268 }
269
270 // If we found our type while recursively processing stuff, just use it.
271 Entry = &MappedTypes[Ty];
272 if (*Entry) return *Entry;
273
274 // If all of the element types mapped directly over, then the type is usable
275 // as-is.
276 if (!AnyChange)
277 return *Entry = Ty;
278
279 // Otherwise, rebuild a modified type.
280 switch (Ty->getTypeID()) {
Craig Topper85814382012-02-07 05:05:23 +0000281 default: llvm_unreachable("unknown derived type to remap");
Chris Lattner1afcace2011-07-09 17:41:24 +0000282 case Type::ArrayTyID:
283 return *Entry = ArrayType::get(ElementTypes[0],
284 cast<ArrayType>(Ty)->getNumElements());
285 case Type::VectorTyID:
286 return *Entry = VectorType::get(ElementTypes[0],
287 cast<VectorType>(Ty)->getNumElements());
288 case Type::PointerTyID:
289 return *Entry = PointerType::get(ElementTypes[0],
290 cast<PointerType>(Ty)->getAddressSpace());
291 case Type::FunctionTyID:
292 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000293 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000294 cast<FunctionType>(Ty)->isVarArg());
295 case Type::StructTyID:
296 // Note that this is only reached for anonymous structs.
297 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
298 cast<StructType>(Ty)->isPacked());
299 }
300 }
301
302 // Otherwise, this is an unmapped named struct. If the struct can be directly
303 // mapped over, just use it as-is. This happens in a case when the linked-in
304 // module has something like:
305 // %T = type {%T*, i32}
306 // @GV = global %T* null
307 // where T does not exist at all in the destination module.
308 //
309 // The other case we watch for is when the type is not in the destination
310 // module, but that it has to be rebuilt because it refers to something that
311 // is already mapped. For example, if the destination module has:
312 // %A = type { i32 }
313 // and the source module has something like
314 // %A' = type { i32 }
315 // %B = type { %A'* }
316 // @GV = global %B* null
317 // then we want to create a new type: "%B = type { %A*}" and have it take the
318 // pristine "%B" name from the source module.
319 //
320 // To determine which case this is, we have to recursively walk the type graph
321 // speculating that we'll be able to reuse it unmodified. Only if this is
322 // safe would we map the entire thing over. Because this is an optimization,
323 // and is not required for the prettiness of the linked module, we just skip
324 // it and always rebuild a type here.
325 StructType *STy = cast<StructType>(Ty);
326
327 // If the type is opaque, we can just use it directly.
328 if (STy->isOpaque())
329 return *Entry = STy;
Bill Wendling601c0942012-02-28 04:01:21 +0000330
Chris Lattner1afcace2011-07-09 17:41:24 +0000331 // Otherwise we create a new type and resolve its body later. This will be
332 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000333 SrcDefinitionsToResolve.push_back(STy);
334 StructType *DTy = StructType::create(STy->getContext());
335 DstResolvedOpaqueTypes.insert(DTy);
336 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000337}
338
Chris Lattner1afcace2011-07-09 17:41:24 +0000339//===----------------------------------------------------------------------===//
340// ModuleLinker implementation.
341//===----------------------------------------------------------------------===//
342
343namespace {
344 /// ModuleLinker - This is an implementation class for the LinkModules
345 /// function, which is the entrypoint for this file.
346 class ModuleLinker {
347 Module *DstM, *SrcM;
348
349 TypeMapTy TypeMap;
350
351 /// ValueMap - Mapping of values from what they used to be in Src, to what
352 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
353 /// some overhead due to the use of Value handles which the Linker doesn't
354 /// actually need, but this allows us to reuse the ValueMapper code.
355 ValueToValueMapTy ValueMap;
356
357 struct AppendingVarInfo {
358 GlobalVariable *NewGV; // New aggregate global in dest module.
359 Constant *DstInit; // Old initializer from dest module.
360 Constant *SrcInit; // Old initializer from src module.
361 };
362
363 std::vector<AppendingVarInfo> AppendingVars;
364
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000365 unsigned Mode; // Mode to treat source module.
366
367 // Set of items not to link in from source.
368 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
369
Tanya Lattner9af37a32011-11-02 00:24:56 +0000370 // Vector of functions to lazily link in.
Bill Wendlingd99a29e2013-03-27 17:54:41 +0000371 std::vector<Function*> LazilyLinkFunctions;
Tanya Lattner9af37a32011-11-02 00:24:56 +0000372
Chris Lattner1afcace2011-07-09 17:41:24 +0000373 public:
374 std::string ErrorMsg;
375
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000376 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
377 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000378
379 bool run();
380
381 private:
382 /// emitError - Helper method for setting a message and returning an error
383 /// code.
384 bool emitError(const Twine &Message) {
385 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000386 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000387 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000388
389 /// getLinkageResult - This analyzes the two global values and determines
390 /// what the result will look like in the destination module.
391 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000392 GlobalValue::LinkageTypes &LT,
393 GlobalValue::VisibilityTypes &Vis,
394 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000395
Chris Lattner1afcace2011-07-09 17:41:24 +0000396 /// getLinkedToGlobal - Given a global in the source module, return the
397 /// global in the destination module that is being linked to, if any.
398 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
399 // If the source has no name it can't link. If it has local linkage,
400 // there is no name match-up going on.
401 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
402 return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000403
Chris Lattner1afcace2011-07-09 17:41:24 +0000404 // Otherwise see if we have a match in the destination module's symtab.
405 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
406 if (DGV == 0) return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000407
Chris Lattner1afcace2011-07-09 17:41:24 +0000408 // If we found a global with the same name in the dest module, but it has
409 // internal linkage, we are really not doing any linkage here.
410 if (DGV->hasLocalLinkage())
411 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413 // Otherwise, we do in fact link to the destination global.
414 return DGV;
415 }
416
417 void computeTypeMapping();
418
419 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
420 bool linkGlobalProto(GlobalVariable *SrcGV);
421 bool linkFunctionProto(Function *SrcF);
422 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000423 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000424
425 void linkAppendingVarInit(const AppendingVarInfo &AVI);
426 void linkGlobalInits();
427 void linkFunctionBody(Function *Dst, Function *Src);
428 void linkAliasBodies();
429 void linkNamedMDNodes();
430 };
Bill Wendling601c0942012-02-28 04:01:21 +0000431}
432
Chris Lattner1afcace2011-07-09 17:41:24 +0000433/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000434/// in the symbol table. This is good for all clients except for us. Go
435/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000436static void forceRenaming(GlobalValue *GV, StringRef Name) {
437 // If the global doesn't force its name or if it already has the right name,
438 // there is nothing for us to do.
439 if (GV->hasLocalLinkage() || GV->getName() == Name)
440 return;
441
442 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000443
444 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000445 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000446 GV->takeName(ConflictGV);
447 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000448 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000449 } else {
450 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000451 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000452}
Reid Spencer8bef0372007-02-04 04:29:21 +0000453
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000454/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000455/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000456static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000457 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
458 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
459 DestGV->copyAttributesFrom(SrcGV);
460 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000461
462 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000463}
464
Rafael Espindola3ed88152012-01-05 23:02:01 +0000465static bool isLessConstraining(GlobalValue::VisibilityTypes a,
466 GlobalValue::VisibilityTypes b) {
467 if (a == GlobalValue::HiddenVisibility)
468 return false;
469 if (b == GlobalValue::HiddenVisibility)
470 return true;
471 if (a == GlobalValue::ProtectedVisibility)
472 return false;
473 if (b == GlobalValue::ProtectedVisibility)
474 return true;
475 return false;
476}
477
Chris Lattner1afcace2011-07-09 17:41:24 +0000478/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000479/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000480/// computes the resultant linkage type and visibility, computes whether the
481/// global in the source should be copied over to the destination (replacing
482/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000483bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000484 GlobalValue::LinkageTypes &LT,
485 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000486 bool &LinkFromSrc) {
487 assert(Dest && "Must have two globals being queried");
488 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000489 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000490
Peter Collingbourne88953162011-10-30 17:46:34 +0000491 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000492 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000493
494 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000495 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000496 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000497 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000498 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000499 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000500 LinkFromSrc = true;
501 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000502 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000503 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000504 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000505 LinkFromSrc = true;
506 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000507 } else {
508 LinkFromSrc = false;
509 LT = Dest->getLinkage();
510 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000511 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000512 // If Dest is external but Src is not:
513 LinkFromSrc = true;
514 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000515 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000516 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
517 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000518 if (Dest->hasExternalWeakLinkage() ||
519 Dest->hasAvailableExternallyLinkage() ||
520 (Dest->hasLinkOnceLinkage() &&
521 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000522 LinkFromSrc = true;
523 LT = Src->getLinkage();
524 } else {
525 LinkFromSrc = false;
526 LT = Dest->getLinkage();
527 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000528 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000529 // At this point we know that Src has External* or DLL* linkage.
530 if (Src->hasExternalWeakLinkage()) {
531 LinkFromSrc = false;
532 LT = Dest->getLinkage();
533 } else {
534 LinkFromSrc = true;
535 LT = GlobalValue::ExternalLinkage;
536 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000537 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000538 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
539 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
540 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
541 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000542 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000543 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000544 "': symbol multiply defined!");
545 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000546
Rafael Espindola3ed88152012-01-05 23:02:01 +0000547 // Compute the visibility. We follow the rules in the System V Application
548 // Binary Interface.
549 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
550 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000551 return false;
552}
Chris Lattner5c377c52001-10-14 23:29:15 +0000553
Chris Lattner1afcace2011-07-09 17:41:24 +0000554/// computeTypeMapping - Loop over all of the linked values to compute type
555/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
556/// we have two struct types 'Foo' but one got renamed when the module was
557/// loaded into the same LLVMContext.
558void ModuleLinker::computeTypeMapping() {
559 // Incorporate globals.
560 for (Module::global_iterator I = SrcM->global_begin(),
561 E = SrcM->global_end(); I != E; ++I) {
562 GlobalValue *DGV = getLinkedToGlobal(I);
563 if (DGV == 0) continue;
564
565 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
566 TypeMap.addTypeMapping(DGV->getType(), I->getType());
567 continue;
568 }
569
570 // Unify the element type of appending arrays.
571 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
572 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
573 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000574 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000575
576 // Incorporate functions.
577 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
578 if (GlobalValue *DGV = getLinkedToGlobal(I))
579 TypeMap.addTypeMapping(DGV->getType(), I->getType());
580 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000581
Bill Wendling601c0942012-02-28 04:01:21 +0000582 // Incorporate types by name, scanning all the types in the source module.
583 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000584 // example. When the source module got loaded into the same LLVMContext, if
585 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling573e9732012-08-03 00:30:35 +0000586 TypeFinder SrcStructTypes;
587 SrcStructTypes.run(*SrcM, true);
Bill Wendling348e5e72012-02-27 23:48:30 +0000588 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
589 SrcStructTypes.end());
Bill Wendlinga20689f2012-03-23 23:17:38 +0000590
Bill Wendling573e9732012-08-03 00:30:35 +0000591 TypeFinder DstStructTypes;
592 DstStructTypes.run(*DstM, true);
Bill Wendlinga20689f2012-03-23 23:17:38 +0000593 SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
594 DstStructTypes.end());
595
Bill Wendling348e5e72012-02-27 23:48:30 +0000596 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
597 StructType *ST = SrcStructTypes[i];
598 if (!ST->hasName()) continue;
599
600 // Check to see if there is a dot in the name followed by a digit.
Bill Wendling601c0942012-02-28 04:01:21 +0000601 size_t DotPos = ST->getName().rfind('.');
602 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000603 ST->getName().back() == '.' ||
604 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendling601c0942012-02-28 04:01:21 +0000605 continue;
Bill Wendling348e5e72012-02-27 23:48:30 +0000606
607 // Check to see if the destination module has a struct with the prefix name.
Bill Wendling601c0942012-02-28 04:01:21 +0000608 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendlinga20689f2012-03-23 23:17:38 +0000609 // Don't use it if this actually came from the source module. They're in
610 // the same LLVMContext after all. Also don't use it unless the type is
611 // actually used in the destination module. This can happen in situations
612 // like this:
613 //
614 // Module A Module B
615 // -------- --------
616 // %Z = type { %A } %B = type { %C.1 }
617 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
618 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
619 // %C = type { i8* } %B.3 = type { %C.1 }
620 //
621 // When we link Module B with Module A, the '%B' in Module B is
622 // used. However, that would then use '%C.1'. But when we process '%C.1',
623 // we prefer to take the '%C' version. So we are then left with both
624 // '%C.1' and '%C' being used for the same types. This leads to some
625 // variables using one type and some using the other.
626 if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
Bill Wendling348e5e72012-02-27 23:48:30 +0000627 TypeMap.addTypeMapping(DST, ST);
628 }
629
Chris Lattner1afcace2011-07-09 17:41:24 +0000630 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendling601c0942012-02-28 04:01:21 +0000631
Chris Lattner1afcace2011-07-09 17:41:24 +0000632 // Now that we have discovered all of the type equivalences, get a body for
633 // any 'opaque' types in the dest module that are now resolved.
634 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000635}
636
Chris Lattner1afcace2011-07-09 17:41:24 +0000637/// linkAppendingVarProto - If there were any appending global variables, link
638/// them together now. Return true on error.
639bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
640 GlobalVariable *SrcGV) {
Bill Wendling601c0942012-02-28 04:01:21 +0000641
Chris Lattner1afcace2011-07-09 17:41:24 +0000642 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
643 return emitError("Linking globals named '" + SrcGV->getName() +
644 "': can only link appending global with another appending global!");
645
646 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
647 ArrayType *SrcTy =
648 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
649 Type *EltTy = DstTy->getElementType();
650
651 // Check to see that they two arrays agree on type.
652 if (EltTy != SrcTy->getElementType())
653 return emitError("Appending variables with different element types!");
654 if (DstGV->isConstant() != SrcGV->isConstant())
655 return emitError("Appending variables linked with different const'ness!");
656
657 if (DstGV->getAlignment() != SrcGV->getAlignment())
658 return emitError(
659 "Appending variables with different alignment need to be linked!");
660
661 if (DstGV->getVisibility() != SrcGV->getVisibility())
662 return emitError(
663 "Appending variables with different visibility need to be linked!");
664
665 if (DstGV->getSection() != SrcGV->getSection())
666 return emitError(
667 "Appending variables with different section name need to be linked!");
668
669 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
670 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
671
672 // Create the new global variable.
673 GlobalVariable *NG =
674 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
675 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000676 DstGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000677 DstGV->getType()->getAddressSpace());
678
679 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000680 copyGVAttributes(NG, DstGV);
Chris Lattner1afcace2011-07-09 17:41:24 +0000681
682 AppendingVarInfo AVI;
683 AVI.NewGV = NG;
684 AVI.DstInit = DstGV->getInitializer();
685 AVI.SrcInit = SrcGV->getInitializer();
686 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000687
Chris Lattner1afcace2011-07-09 17:41:24 +0000688 // Replace any uses of the two global variables with uses of the new
689 // global.
690 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000691
Chris Lattner1afcace2011-07-09 17:41:24 +0000692 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
693 DstGV->eraseFromParent();
694
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000695 // Track the source variable so we don't try to link it.
696 DoNotLinkFromSource.insert(SrcGV);
697
Chris Lattner1afcace2011-07-09 17:41:24 +0000698 return false;
699}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000700
Chris Lattner1afcace2011-07-09 17:41:24 +0000701/// linkGlobalProto - Loop through the global variables in the src module and
702/// merge them into the dest module.
703bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
704 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000705 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000706
Chris Lattner1afcace2011-07-09 17:41:24 +0000707 if (DGV) {
708 // Concatenation of appending linkage variables is magic and handled later.
709 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
710 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
711
712 // Determine whether linkage of these two globals follows the source
713 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000714 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000715 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000716 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000717 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000718 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000719 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000720
Chris Lattner1afcace2011-07-09 17:41:24 +0000721 // If we're not linking from the source, then keep the definition that we
722 // have.
723 if (!LinkFromSrc) {
724 // Special case for const propagation.
725 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
726 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
727 DGVar->setConstant(true);
728
Rafael Espindola3ed88152012-01-05 23:02:01 +0000729 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000730 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000731 DGV->setVisibility(*NewVisibility);
732
Chris Lattner6157e382008-07-14 07:23:24 +0000733 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000734 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
735
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000736 // Track the source global so that we don't attempt to copy it over when
737 // processing global initializers.
738 DoNotLinkFromSource.insert(SGV);
739
Chris Lattner1afcace2011-07-09 17:41:24 +0000740 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000741 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000742 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000743
744 // No linking to be performed or linking from the source: simply create an
745 // identical version of the symbol over in the dest module... the
746 // initializer will be filled in later by LinkGlobalInits.
747 GlobalVariable *NewDGV =
748 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
749 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
750 SGV->getName(), /*insertbefore*/0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000751 SGV->getThreadLocalMode(),
Chris Lattner1afcace2011-07-09 17:41:24 +0000752 SGV->getType()->getAddressSpace());
753 // Propagate alignment, visibility and section info.
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000754 copyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000755 if (NewVisibility)
756 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000757
758 if (DGV) {
759 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
760 DGV->eraseFromParent();
761 }
762
763 // Make sure to remember this mapping.
764 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000765 return false;
766}
767
Chris Lattner1afcace2011-07-09 17:41:24 +0000768/// linkFunctionProto - Link the function in the source module into the
769/// destination module if needed, setting up mapping information.
770bool ModuleLinker::linkFunctionProto(Function *SF) {
771 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000772 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000773
774 if (DGV) {
775 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
776 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000777 GlobalValue::VisibilityTypes NV;
778 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000779 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000780 NewVisibility = NV;
781
Chris Lattner1afcace2011-07-09 17:41:24 +0000782 if (!LinkFromSrc) {
783 // Set calculated linkage
784 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000785 DGV->setVisibility(*NewVisibility);
786
Chris Lattner1afcace2011-07-09 17:41:24 +0000787 // Make sure to remember this mapping.
788 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
789
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000790 // Track the function from the source module so we don't attempt to remap
791 // it.
792 DoNotLinkFromSource.insert(SF);
793
Chris Lattner1afcace2011-07-09 17:41:24 +0000794 return false;
795 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000796 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000797
798 // If there is no linkage to be performed or we are linking from the source,
799 // bring SF over.
800 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
801 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000802 copyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000803 if (NewVisibility)
804 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000805
Chris Lattner1afcace2011-07-09 17:41:24 +0000806 if (DGV) {
807 // Any uses of DF need to change to NewDF, with cast.
808 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
809 DGV->eraseFromParent();
Bill Wendlingd99a29e2013-03-27 17:54:41 +0000810 } else {
811 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
812 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
813 SF->hasAvailableExternallyLinkage()) {
814 DoNotLinkFromSource.insert(SF);
815 LazilyLinkFunctions.push_back(SF);
816 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000817 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000818
819 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000820 return false;
821}
822
Chris Lattner1afcace2011-07-09 17:41:24 +0000823/// LinkAliasProto - Set up prototypes for any aliases that come over from the
824/// source module.
825bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
826 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000827 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
828
Chris Lattner1afcace2011-07-09 17:41:24 +0000829 if (DGV) {
830 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000831 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000832 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000833 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000834 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000835 NewVisibility = NV;
836
Chris Lattner1afcace2011-07-09 17:41:24 +0000837 if (!LinkFromSrc) {
838 // Set calculated linkage.
839 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000840 DGV->setVisibility(*NewVisibility);
841
Chris Lattner1afcace2011-07-09 17:41:24 +0000842 // Make sure to remember this mapping.
843 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
844
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000845 // Track the alias from the source module so we don't attempt to remap it.
846 DoNotLinkFromSource.insert(SGA);
847
Chris Lattner1afcace2011-07-09 17:41:24 +0000848 return false;
849 }
850 }
851
852 // If there is no linkage to be performed or we're linking from the source,
853 // bring over SGA.
854 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
855 SGA->getLinkage(), SGA->getName(),
856 /*aliasee*/0, DstM);
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000857 copyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000858 if (NewVisibility)
859 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000860
Chris Lattner1afcace2011-07-09 17:41:24 +0000861 if (DGV) {
862 // Any uses of DGV need to change to NewDA, with cast.
863 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
864 DGV->eraseFromParent();
865 }
866
867 ValueMap[SGA] = NewDA;
868 return false;
869}
870
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000871static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000872 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
873
874 for (unsigned i = 0; i != NumElements; ++i)
875 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000876}
877
Chris Lattner1afcace2011-07-09 17:41:24 +0000878void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
879 // Merge the initializer.
880 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000881 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000882
883 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000884 getArrayElements(SrcInit, Elements);
885
Chris Lattner1afcace2011-07-09 17:41:24 +0000886 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
887 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
888}
889
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000890/// linkGlobalInits - Update the initializers in the Dest module now that all
891/// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000892void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000893 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000894 for (Module::const_global_iterator I = SrcM->global_begin(),
895 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000896
897 // Only process initialized GV's or ones not already in dest.
898 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000899
900 // Grab destination global variable.
901 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
902 // Figure out what the initializer looks like in the dest module.
903 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
904 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000905 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000906}
Chris Lattner5c377c52001-10-14 23:29:15 +0000907
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000908/// linkFunctionBody - Copy the source function over into the dest function and
909/// fix up references to values. At this point we know that Dest is an external
910/// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000911void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
912 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000913
Chris Lattner0033baf2004-11-16 17:12:38 +0000914 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000915 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000916 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000917 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000918 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000919
Chris Lattner1afcace2011-07-09 17:41:24 +0000920 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000921 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000922 }
923
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000924 if (Mode == Linker::DestroySource) {
925 // Splice the body of the source function into the dest function.
926 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
927
928 // At this point, all of the instructions and values of the function are now
929 // copied over. The only problem is that they are still referencing values in
930 // the Source function as operands. Loop through all of the operands of the
931 // functions and patch them up to point to the local versions.
932 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
933 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
934 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
935
936 } else {
937 // Clone the body of the function into the dest function.
938 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000939 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000940 }
941
Chris Lattner0033baf2004-11-16 17:12:38 +0000942 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000943 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
944 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000945 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000946
Chris Lattner5c377c52001-10-14 23:29:15 +0000947}
948
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000949/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattner1afcace2011-07-09 17:41:24 +0000950void ModuleLinker::linkAliasBodies() {
951 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000952 I != E; ++I) {
953 if (DoNotLinkFromSource.count(I))
954 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000955 if (Constant *Aliasee = I->getAliasee()) {
956 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
957 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000958 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000959 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000960}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000961
Bill Wendlingcd7193f2012-03-22 20:28:27 +0000962/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattner1afcace2011-07-09 17:41:24 +0000963/// module.
964void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000965 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000966 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
967 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000968 // Don't link module flags here. Do them separately.
969 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000970 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
971 // Add Src elements into Dest node.
972 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
973 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
974 RF_None, &TypeMap));
975 }
976}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000977
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000978/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
979/// module.
980bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar1e081652013-01-16 18:39:23 +0000981 // If the source module has no module flags, we are done.
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000982 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
983 if (!SrcModFlags) return false;
984
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000985 // If the destination module doesn't have module flags yet, then just copy
986 // over the source module's flags.
Daniel Dunbar1e081652013-01-16 18:39:23 +0000987 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000988 if (DstModFlags->getNumOperands() == 0) {
989 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
990 DstModFlags->addOperand(SrcModFlags->getOperand(I));
991
992 return false;
993 }
994
Daniel Dunbar1e081652013-01-16 18:39:23 +0000995 // First build a map of the existing module flags and requirements.
996 DenseMap<MDString*, MDNode*> Flags;
997 SmallSetVector<MDNode*, 16> Requirements;
998 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
999 MDNode *Op = DstModFlags->getOperand(I);
1000 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1001 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001002
Daniel Dunbar1e081652013-01-16 18:39:23 +00001003 if (Behavior->getZExtValue() == Module::Require) {
1004 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1005 } else {
1006 Flags[ID] = Op;
1007 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001008 }
1009
Daniel Dunbar1e081652013-01-16 18:39:23 +00001010 // Merge in the flags from the source module, and also collect its set of
1011 // requirements.
1012 bool HasErr = false;
1013 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1014 MDNode *SrcOp = SrcModFlags->getOperand(I);
1015 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1016 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1017 MDNode *DstOp = Flags.lookup(ID);
1018 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001019
Daniel Dunbar1e081652013-01-16 18:39:23 +00001020 // If this is a requirement, add it and continue.
1021 if (SrcBehaviorValue == Module::Require) {
1022 // If the destination module does not already have this requirement, add
1023 // it.
1024 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1025 DstModFlags->addOperand(SrcOp);
1026 }
1027 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001028 }
1029
Daniel Dunbar1e081652013-01-16 18:39:23 +00001030 // If there is no existing flag with this ID, just add it.
1031 if (!DstOp) {
1032 Flags[ID] = SrcOp;
1033 DstModFlags->addOperand(SrcOp);
1034 continue;
1035 }
1036
1037 // Otherwise, perform a merge.
1038 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1039 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1040
1041 // If either flag has override behavior, handle it first.
1042 if (DstBehaviorValue == Module::Override) {
1043 // Diagnose inconsistent flags which both have override behavior.
1044 if (SrcBehaviorValue == Module::Override &&
1045 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1046 HasErr |= emitError("linking module flags '" + ID->getString() +
1047 "': IDs have conflicting override values");
1048 }
1049 continue;
1050 } else if (SrcBehaviorValue == Module::Override) {
1051 // Update the destination flag to that of the source.
1052 DstOp->replaceOperandWith(0, SrcBehavior);
1053 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1054 continue;
1055 }
1056
1057 // Diagnose inconsistent merge behavior types.
1058 if (SrcBehaviorValue != DstBehaviorValue) {
1059 HasErr |= emitError("linking module flags '" + ID->getString() +
1060 "': IDs have conflicting behaviors");
1061 continue;
1062 }
1063
1064 // Perform the merge for standard behavior types.
1065 switch (SrcBehaviorValue) {
1066 case Module::Require:
1067 case Module::Override: assert(0 && "not possible"); break;
1068 case Module::Error: {
1069 // Emit an error if the values differ.
1070 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1071 HasErr |= emitError("linking module flags '" + ID->getString() +
1072 "': IDs have conflicting values");
1073 }
1074 continue;
1075 }
1076 case Module::Warning: {
1077 // Emit a warning if the values differ.
1078 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1079 errs() << "WARNING: linking module flags '" << ID->getString()
1080 << "': IDs have conflicting values";
1081 }
1082 continue;
1083 }
Daniel Dunbar5db391c2013-01-16 21:38:56 +00001084 case Module::Append: {
1085 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1086 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1087 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1088 Value **VP, **Values = VP = new Value*[NumOps];
1089 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1090 *VP = DstValue->getOperand(i);
1091 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1092 *VP = SrcValue->getOperand(i);
1093 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1094 ArrayRef<Value*>(Values,
1095 NumOps)));
1096 delete[] Values;
1097 break;
1098 }
1099 case Module::AppendUnique: {
1100 SmallSetVector<Value*, 16> Elts;
1101 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1102 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1103 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1104 Elts.insert(DstValue->getOperand(i));
1105 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1106 Elts.insert(SrcValue->getOperand(i));
1107 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1108 ArrayRef<Value*>(Elts.begin(),
1109 Elts.end())));
1110 break;
1111 }
Daniel Dunbar1e081652013-01-16 18:39:23 +00001112 }
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001113 }
1114
Daniel Dunbar1e081652013-01-16 18:39:23 +00001115 // Check all of the requirements.
1116 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1117 MDNode *Requirement = Requirements[I];
1118 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1119 Value *ReqValue = Requirement->getOperand(1);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001120
Daniel Dunbar1e081652013-01-16 18:39:23 +00001121 MDNode *Op = Flags[Flag];
1122 if (!Op || Op->getOperand(2) != ReqValue) {
1123 HasErr |= emitError("linking module flags '" + Flag->getString() +
1124 "': does not have the required value");
1125 continue;
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001126 }
1127 }
1128
1129 return HasErr;
1130}
Chris Lattner1afcace2011-07-09 17:41:24 +00001131
1132bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001133 assert(DstM && "Null destination module");
1134 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001135
1136 // Inherit the target data from the source module if the destination module
1137 // doesn't have one already.
1138 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1139 DstM->setDataLayout(SrcM->getDataLayout());
1140
1141 // Copy the target triple from the source to dest if the dest's is empty.
1142 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1143 DstM->setTargetTriple(SrcM->getTargetTriple());
1144
1145 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1146 SrcM->getDataLayout() != DstM->getDataLayout())
1147 errs() << "WARNING: Linking two modules of different data layouts!\n";
1148 if (!SrcM->getTargetTriple().empty() &&
1149 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1150 errs() << "WARNING: Linking two modules of different target triples: ";
1151 if (!SrcM->getModuleIdentifier().empty())
1152 errs() << SrcM->getModuleIdentifier() << ": ";
1153 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1154 << DstM->getTargetTriple() << "'\n";
1155 }
1156
1157 // Append the module inline asm string.
1158 if (!SrcM->getModuleInlineAsm().empty()) {
1159 if (DstM->getModuleInlineAsm().empty())
1160 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1161 else
1162 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1163 SrcM->getModuleInlineAsm());
1164 }
1165
Chris Lattner1afcace2011-07-09 17:41:24 +00001166 // Loop over all of the linked values to compute type mappings.
1167 computeTypeMapping();
1168
1169 // Insert all of the globals in src into the DstM module... without linking
1170 // initializers (which could refer to functions not yet mapped over).
1171 for (Module::global_iterator I = SrcM->global_begin(),
1172 E = SrcM->global_end(); I != E; ++I)
1173 if (linkGlobalProto(I))
1174 return true;
1175
1176 // Link the functions together between the two modules, without doing function
1177 // bodies... this just adds external function prototypes to the DstM
1178 // function... We do this so that when we begin processing function bodies,
1179 // all of the global values that may be referenced are available in our
1180 // ValueMap.
1181 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1182 if (linkFunctionProto(I))
1183 return true;
1184
1185 // If there were any aliases, link them now.
1186 for (Module::alias_iterator I = SrcM->alias_begin(),
1187 E = SrcM->alias_end(); I != E; ++I)
1188 if (linkAliasProto(I))
1189 return true;
1190
1191 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1192 linkAppendingVarInit(AppendingVars[i]);
1193
1194 // Update the initializers in the DstM module now that all globals that may
1195 // be referenced are in DstM.
1196 linkGlobalInits();
1197
1198 // Link in the function bodies that are defined in the source module into
1199 // DstM.
1200 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001201 // Skip if not linking from source.
1202 if (DoNotLinkFromSource.count(SF)) continue;
1203
1204 // Skip if no body (function is external) or materialize.
1205 if (SF->isDeclaration()) {
1206 if (!SF->isMaterializable())
1207 continue;
1208 if (SF->Materialize(&ErrorMsg))
1209 return true;
1210 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001211
1212 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001213 SF->Dematerialize();
Chris Lattner1afcace2011-07-09 17:41:24 +00001214 }
1215
1216 // Resolve all uses of aliases with aliasees.
1217 linkAliasBodies();
1218
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001219 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001220 // after linking GlobalValues so that MDNodes that reference GlobalValues
1221 // are properly remapped.
1222 linkNamedMDNodes();
1223
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001224 // Merge the module flags into the DstM module.
1225 if (linkModuleFlagsMetadata())
1226 return true;
1227
Tanya Lattner9af37a32011-11-02 00:24:56 +00001228 // Process vector of lazily linked in functions.
1229 bool LinkedInAnyFunctions;
1230 do {
1231 LinkedInAnyFunctions = false;
1232
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001233 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1234 E = LazilyLinkFunctions.end(); I != E; ++I) {
1235 if (!*I)
Tanya Lattner9af37a32011-11-02 00:24:56 +00001236 continue;
1237
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001238 Function *SF = *I;
1239 Function *DF = cast<Function>(ValueMap[SF]);
1240
1241 if (!DF->use_empty()) {
1242
Tanya Lattner9af37a32011-11-02 00:24:56 +00001243 // Materialize if necessary.
1244 if (SF->isDeclaration()) {
1245 if (!SF->isMaterializable())
1246 continue;
1247 if (SF->Materialize(&ErrorMsg))
1248 return true;
1249 }
1250
1251 // Link in function body.
1252 linkFunctionBody(DF, SF);
Bill Wendling208b6f62012-03-23 07:22:49 +00001253 SF->Dematerialize();
1254
Tanya Lattner9af37a32011-11-02 00:24:56 +00001255 // "Remove" from vector by setting the element to 0.
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001256 *I = 0;
Tanya Lattner9af37a32011-11-02 00:24:56 +00001257
1258 // Set flag to indicate we may have more functions to lazily link in
1259 // since we linked in a function.
1260 LinkedInAnyFunctions = true;
1261 }
1262 }
1263 } while (LinkedInAnyFunctions);
1264
Bill Wendlingd99a29e2013-03-27 17:54:41 +00001265 // Remove any prototypes of functions that were not actually linked in.
1266 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1267 E = LazilyLinkFunctions.end(); I != E; ++I) {
1268 if (!*I)
1269 continue;
1270
1271 Function *SF = *I;
1272 Function *DF = cast<Function>(ValueMap[SF]);
1273 if (DF->use_empty())
1274 DF->eraseFromParent();
1275 }
1276
Chris Lattner1afcace2011-07-09 17:41:24 +00001277 // Now that all of the types from the source are used, resolve any structs
1278 // copied over to the dest that didn't exist there.
1279 TypeMap.linkDefinedTypeBodies();
1280
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001281 return false;
1282}
Chris Lattner52f7e902001-10-13 07:03:50 +00001283
Rafael Espindolac7c35a92013-05-04 03:48:37 +00001284Linker::Linker(Module *M) : Composite(M) {}
1285
1286Linker::~Linker() {
1287}
1288
1289bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1290 return LinkModules(Composite, Src, Linker::DestroySource, ErrorMsg);
1291}
1292
Chris Lattner1afcace2011-07-09 17:41:24 +00001293//===----------------------------------------------------------------------===//
1294// LinkModules entrypoint.
1295//===----------------------------------------------------------------------===//
1296
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001297/// LinkModules - This function links two modules together, with the resulting
Eli Benderskyd25c05e2013-03-08 22:29:44 +00001298/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingcd7193f2012-03-22 20:28:27 +00001299/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1300/// the problem. Upon failure, the Dest module could be in a modified state,
1301/// and shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001302bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1303 std::string *ErrorMsg) {
1304 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001305 if (TheLinker.run()) {
1306 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001307 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001308 }
Bill Wendlinga20689f2012-03-23 23:17:38 +00001309
Chris Lattner52f7e902001-10-13 07:03:50 +00001310 return false;
1311}
Bill Wendlingf24fde22012-05-09 08:55:40 +00001312
1313//===----------------------------------------------------------------------===//
1314// C API.
1315//===----------------------------------------------------------------------===//
1316
1317LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1318 LLVMLinkerMode Mode, char **OutMessages) {
1319 std::string Messages;
1320 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1321 Mode, OutMessages? &Messages : 0);
1322 if (OutMessages)
1323 *OutMessages = strdup(Messages.c_str());
1324 return Result;
1325}