blob: 7706b9064e5d865df75538496bb8c9f6f1b64e62 [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"
Chris Lattneradbc0b52003-11-20 18:23:14 +000015#include "llvm/Constants.h"
16#include "llvm/DerivedTypes.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000017#include "llvm/Instructions.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000018#include "llvm/Module.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000019#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner74382b72009-08-23 22:45:37 +000020#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000021#include "llvm/Support/Path.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000022#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000023#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Chris Lattner1afcace2011-07-09 17:41:24 +000026//===----------------------------------------------------------------------===//
27// TypeMap implementation.
28//===----------------------------------------------------------------------===//
Chris Lattner5c377c52001-10-14 23:29:15 +000029
Chris Lattner62a81a12008-06-16 21:00:18 +000030namespace {
Chris Lattner1afcace2011-07-09 17:41:24 +000031class TypeMapTy : public ValueMapTypeRemapper {
32 /// MappedTypes - This is a mapping from a source type to a destination type
33 /// to use.
34 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000035
Chris Lattner1afcace2011-07-09 17:41:24 +000036 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
37 /// we speculatively add types to MappedTypes, but keep track of them here in
38 /// case we need to roll back.
39 SmallVector<Type*, 16> SpeculativeTypes;
40
Chris Lattner68910502011-12-20 00:03:52 +000041 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
42 /// source module that are mapped to an opaque struct in the destination
43 /// module.
44 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
45
46 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
47 /// destination modules who are getting a body from the source module.
48 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Chris Lattnerfc196f92008-06-16 23:06:51 +000049public:
Chris Lattner1afcace2011-07-09 17:41:24 +000050
51 /// addTypeMapping - Indicate that the specified type in the destination
52 /// module is conceptually equivalent to the specified type in the source
53 /// module.
54 void addTypeMapping(Type *DstTy, Type *SrcTy);
55
56 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
57 /// module from a type definition in the source module.
58 void linkDefinedTypeBodies();
59
60 /// get - Return the mapped type to use for the specified input type from the
61 /// source module.
62 Type *get(Type *SrcTy);
63
64 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
65
66private:
67 Type *getImpl(Type *T);
68 /// remapType - Implement the ValueMapTypeRemapper interface.
69 Type *remapType(Type *SrcTy) {
70 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000071 }
Chris Lattner1afcace2011-07-09 17:41:24 +000072
73 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000074};
75}
76
Chris Lattner1afcace2011-07-09 17:41:24 +000077void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
78 Type *&Entry = MappedTypes[SrcTy];
79 if (Entry) return;
80
81 if (DstTy == SrcTy) {
82 Entry = DstTy;
83 return;
84 }
85
86 // Check to see if these types are recursively isomorphic and establish a
87 // mapping between them if so.
88 if (!areTypesIsomorphic(DstTy, SrcTy)) {
89 // Oops, they aren't isomorphic. Just discard this request by rolling out
90 // any speculative mappings we've established.
91 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
92 MappedTypes.erase(SpeculativeTypes[i]);
93 }
94 SpeculativeTypes.clear();
95}
Chris Lattner62a81a12008-06-16 21:00:18 +000096
Chris Lattner1afcace2011-07-09 17:41:24 +000097/// areTypesIsomorphic - Recursively walk this pair of types, returning true
98/// if they are isomorphic, false if they are not.
99bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
100 // Two types with differing kinds are clearly not isomorphic.
101 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000102
Chris Lattner1afcace2011-07-09 17:41:24 +0000103 // If we have an entry in the MappedTypes table, then we have our answer.
104 Type *&Entry = MappedTypes[SrcTy];
105 if (Entry)
106 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000107
Chris Lattner1afcace2011-07-09 17:41:24 +0000108 // Two identical types are clearly isomorphic. Remember this
109 // non-speculatively.
110 if (DstTy == SrcTy) {
111 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000112 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000113 }
114
115 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000116
Chris Lattner1afcace2011-07-09 17:41:24 +0000117 // If this is an opaque struct type, special case it.
118 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
119 // Mapping an opaque type to any struct, just keep the dest struct.
120 if (SSTy->isOpaque()) {
121 Entry = DstTy;
122 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000123 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000124 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000125
Chris Lattner68910502011-12-20 00:03:52 +0000126 // Mapping a non-opaque source type to an opaque dest. If this is the first
127 // type that we're mapping onto this destination type then we succeed. Keep
128 // the dest, but fill it in later. This doesn't need to be speculative. If
129 // this is the second (different) type that we're trying to map onto the
130 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000131 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000132 // We can only map one source type onto the opaque destination type.
133 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
134 return false;
135 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000136 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000137 return true;
138 }
139 }
140
141 // If the number of subtypes disagree between the two types, then we fail.
142 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000143 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000144
145 // Fail if any of the extra properties (e.g. array size) of the type disagree.
146 if (isa<IntegerType>(DstTy))
147 return false; // bitwidth disagrees.
148 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
149 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
150 return false;
151 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
152 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
153 return false;
154 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
155 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000156 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000157 DSTy->isPacked() != SSTy->isPacked())
158 return false;
159 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
160 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
161 return false;
162 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
163 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
164 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000165 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000166
167 // Otherwise, we speculate that these two types will line up and recursively
168 // check the subelements.
169 Entry = DstTy;
170 SpeculativeTypes.push_back(SrcTy);
171
172 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
173 if (!areTypesIsomorphic(DstTy->getContainedType(i),
174 SrcTy->getContainedType(i)))
175 return false;
176
177 // If everything seems to have lined up, then everything is great.
178 return true;
179}
180
181/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
182/// module from a type definition in the source module.
183void TypeMapTy::linkDefinedTypeBodies() {
184 SmallVector<Type*, 16> Elements;
185 SmallString<16> TmpName;
186
187 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000188 // entries to the SrcDefinitionsToResolve vector.
189 while (!SrcDefinitionsToResolve.empty()) {
190 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000191 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
192
193 // TypeMap is a many-to-one mapping, if there were multiple types that
194 // provide a body for DstSTy then previous iterations of this loop may have
195 // already handled it. Just ignore this case.
196 if (!DstSTy->isOpaque()) continue;
197 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
198
199 // Map the body of the source type over to a new body for the dest type.
200 Elements.resize(SrcSTy->getNumElements());
201 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
202 Elements[i] = getImpl(SrcSTy->getElementType(i));
203
204 DstSTy->setBody(Elements, SrcSTy->isPacked());
205
206 // If DstSTy has no name or has a longer name than STy, then viciously steal
207 // STy's name.
208 if (!SrcSTy->hasName()) continue;
209 StringRef SrcName = SrcSTy->getName();
210
211 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
212 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
213 SrcSTy->setName("");
214 DstSTy->setName(TmpName.str());
215 TmpName.clear();
216 }
217 }
Chris Lattner68910502011-12-20 00:03:52 +0000218
219 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000220}
221
222
223/// get - Return the mapped type to use for the specified input type from the
224/// source module.
225Type *TypeMapTy::get(Type *Ty) {
226 Type *Result = getImpl(Ty);
227
228 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner68910502011-12-20 00:03:52 +0000229 if (!SrcDefinitionsToResolve.empty())
Chris Lattner1afcace2011-07-09 17:41:24 +0000230 linkDefinedTypeBodies();
231 return Result;
232}
233
234/// getImpl - This is the recursive version of get().
235Type *TypeMapTy::getImpl(Type *Ty) {
236 // If we already have an entry for this type, return it.
237 Type **Entry = &MappedTypes[Ty];
238 if (*Entry) return *Entry;
239
240 // If this is not a named struct type, then just map all of the elements and
241 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000242 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000243 // If there are no element types to map, then the type is itself. This is
244 // true for the anonymous {} struct, things like 'float', integers, etc.
245 if (Ty->getNumContainedTypes() == 0)
246 return *Entry = Ty;
247
248 // Remap all of the elements, keeping track of whether any of them change.
249 bool AnyChange = false;
250 SmallVector<Type*, 4> ElementTypes;
251 ElementTypes.resize(Ty->getNumContainedTypes());
252 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
253 ElementTypes[i] = getImpl(Ty->getContainedType(i));
254 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
255 }
256
257 // If we found our type while recursively processing stuff, just use it.
258 Entry = &MappedTypes[Ty];
259 if (*Entry) return *Entry;
260
261 // If all of the element types mapped directly over, then the type is usable
262 // as-is.
263 if (!AnyChange)
264 return *Entry = Ty;
265
266 // Otherwise, rebuild a modified type.
267 switch (Ty->getTypeID()) {
268 default: assert(0 && "unknown derived type to remap");
269 case Type::ArrayTyID:
270 return *Entry = ArrayType::get(ElementTypes[0],
271 cast<ArrayType>(Ty)->getNumElements());
272 case Type::VectorTyID:
273 return *Entry = VectorType::get(ElementTypes[0],
274 cast<VectorType>(Ty)->getNumElements());
275 case Type::PointerTyID:
276 return *Entry = PointerType::get(ElementTypes[0],
277 cast<PointerType>(Ty)->getAddressSpace());
278 case Type::FunctionTyID:
279 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000280 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000281 cast<FunctionType>(Ty)->isVarArg());
282 case Type::StructTyID:
283 // Note that this is only reached for anonymous structs.
284 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
285 cast<StructType>(Ty)->isPacked());
286 }
287 }
288
289 // Otherwise, this is an unmapped named struct. If the struct can be directly
290 // mapped over, just use it as-is. This happens in a case when the linked-in
291 // module has something like:
292 // %T = type {%T*, i32}
293 // @GV = global %T* null
294 // where T does not exist at all in the destination module.
295 //
296 // The other case we watch for is when the type is not in the destination
297 // module, but that it has to be rebuilt because it refers to something that
298 // is already mapped. For example, if the destination module has:
299 // %A = type { i32 }
300 // and the source module has something like
301 // %A' = type { i32 }
302 // %B = type { %A'* }
303 // @GV = global %B* null
304 // then we want to create a new type: "%B = type { %A*}" and have it take the
305 // pristine "%B" name from the source module.
306 //
307 // To determine which case this is, we have to recursively walk the type graph
308 // speculating that we'll be able to reuse it unmodified. Only if this is
309 // safe would we map the entire thing over. Because this is an optimization,
310 // and is not required for the prettiness of the linked module, we just skip
311 // it and always rebuild a type here.
312 StructType *STy = cast<StructType>(Ty);
313
314 // If the type is opaque, we can just use it directly.
315 if (STy->isOpaque())
316 return *Entry = STy;
317
318 // Otherwise we create a new type and resolve its body later. This will be
319 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000320 SrcDefinitionsToResolve.push_back(STy);
321 StructType *DTy = StructType::create(STy->getContext());
322 DstResolvedOpaqueTypes.insert(DTy);
323 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000324}
325
326
327
328//===----------------------------------------------------------------------===//
329// ModuleLinker implementation.
330//===----------------------------------------------------------------------===//
331
332namespace {
333 /// ModuleLinker - This is an implementation class for the LinkModules
334 /// function, which is the entrypoint for this file.
335 class ModuleLinker {
336 Module *DstM, *SrcM;
337
338 TypeMapTy TypeMap;
339
340 /// ValueMap - Mapping of values from what they used to be in Src, to what
341 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
342 /// some overhead due to the use of Value handles which the Linker doesn't
343 /// actually need, but this allows us to reuse the ValueMapper code.
344 ValueToValueMapTy ValueMap;
345
346 struct AppendingVarInfo {
347 GlobalVariable *NewGV; // New aggregate global in dest module.
348 Constant *DstInit; // Old initializer from dest module.
349 Constant *SrcInit; // Old initializer from src module.
350 };
351
352 std::vector<AppendingVarInfo> AppendingVars;
353
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000354 unsigned Mode; // Mode to treat source module.
355
356 // Set of items not to link in from source.
357 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
358
Tanya Lattner9af37a32011-11-02 00:24:56 +0000359 // Vector of functions to lazily link in.
360 std::vector<Function*> LazilyLinkFunctions;
361
Chris Lattner1afcace2011-07-09 17:41:24 +0000362 public:
363 std::string ErrorMsg;
364
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000365 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
366 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000367
368 bool run();
369
370 private:
371 /// emitError - Helper method for setting a message and returning an error
372 /// code.
373 bool emitError(const Twine &Message) {
374 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000375 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000376 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000377
378 /// getLinkageResult - This analyzes the two global values and determines
379 /// what the result will look like in the destination module.
380 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
381 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000382
Chris Lattner1afcace2011-07-09 17:41:24 +0000383 /// getLinkedToGlobal - Given a global in the source module, return the
384 /// global in the destination module that is being linked to, if any.
385 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
386 // If the source has no name it can't link. If it has local linkage,
387 // there is no name match-up going on.
388 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
389 return 0;
390
391 // Otherwise see if we have a match in the destination module's symtab.
392 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
393 if (DGV == 0) return 0;
394
395 // If we found a global with the same name in the dest module, but it has
396 // internal linkage, we are really not doing any linkage here.
397 if (DGV->hasLocalLinkage())
398 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000399
Chris Lattner1afcace2011-07-09 17:41:24 +0000400 // Otherwise, we do in fact link to the destination global.
401 return DGV;
402 }
403
404 void computeTypeMapping();
405
406 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
407 bool linkGlobalProto(GlobalVariable *SrcGV);
408 bool linkFunctionProto(Function *SrcF);
409 bool linkAliasProto(GlobalAlias *SrcA);
410
411 void linkAppendingVarInit(const AppendingVarInfo &AVI);
412 void linkGlobalInits();
413 void linkFunctionBody(Function *Dst, Function *Src);
414 void linkAliasBodies();
415 void linkNamedMDNodes();
416 };
Chris Lattnere3092c92003-08-23 21:25:54 +0000417}
418
Chris Lattnere76c57a2003-08-22 06:07:12 +0000419
Chris Lattner2c236f32001-11-03 05:18:24 +0000420
Chris Lattner1afcace2011-07-09 17:41:24 +0000421/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000422/// in the symbol table. This is good for all clients except for us. Go
423/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000424static void forceRenaming(GlobalValue *GV, StringRef Name) {
425 // If the global doesn't force its name or if it already has the right name,
426 // there is nothing for us to do.
427 if (GV->hasLocalLinkage() || GV->getName() == Name)
428 return;
429
430 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000431
432 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000433 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000434 GV->takeName(ConflictGV);
435 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000436 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000437 } else {
438 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000439 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000440}
Reid Spencer8bef0372007-02-04 04:29:21 +0000441
Reid Spenceref9b9a72007-02-05 20:47:22 +0000442/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000443/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000444static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000445 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
446 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
447 DestGV->copyAttributesFrom(SrcGV);
448 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000449
450 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000451}
452
Chris Lattner1afcace2011-07-09 17:41:24 +0000453/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000454/// the result will look like in the destination module. In particular, it
455/// computes the resultant linkage type, computes whether the global in the
456/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000457/// one), and computes whether this linkage is an error or not. It also performs
458/// visibility checks: we cannot link together two symbols with different
459/// visibilities.
Chris Lattner1afcace2011-07-09 17:41:24 +0000460bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
461 GlobalValue::LinkageTypes &LT,
462 bool &LinkFromSrc) {
463 assert(Dest && "Must have two globals being queried");
464 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000465 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000466
Peter Collingbourne88953162011-10-30 17:46:34 +0000467 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000468 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000469
470 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000471 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000472 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000473 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000474 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000475 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000476 LinkFromSrc = true;
477 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000478 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000479 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000480 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000481 LinkFromSrc = true;
482 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000483 } else {
484 LinkFromSrc = false;
485 LT = Dest->getLinkage();
486 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000487 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000488 // If Dest is external but Src is not:
489 LinkFromSrc = true;
490 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000491 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000492 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
493 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000494 if (Dest->hasExternalWeakLinkage() ||
495 Dest->hasAvailableExternallyLinkage() ||
496 (Dest->hasLinkOnceLinkage() &&
497 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000498 LinkFromSrc = true;
499 LT = Src->getLinkage();
500 } else {
501 LinkFromSrc = false;
502 LT = Dest->getLinkage();
503 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000504 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000505 // At this point we know that Src has External* or DLL* linkage.
506 if (Src->hasExternalWeakLinkage()) {
507 LinkFromSrc = false;
508 LT = Dest->getLinkage();
509 } else {
510 LinkFromSrc = true;
511 LT = GlobalValue::ExternalLinkage;
512 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000513 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000514 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
515 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
516 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
517 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000518 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000519 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000520 "': symbol multiply defined!");
521 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000522
523 // Check visibility
Chris Lattner1afcace2011-07-09 17:41:24 +0000524 if (Src->getVisibility() != Dest->getVisibility() &&
525 !SrcIsDeclaration && !DestIsDeclaration &&
Rafael Espindola4e938852011-02-01 05:33:52 +0000526 !Src->hasAvailableExternallyLinkage() &&
527 !Dest->hasAvailableExternallyLinkage())
Chris Lattner1afcace2011-07-09 17:41:24 +0000528 return emitError("Linking globals named '" + Src->getName() +
Chris Lattner97f8b092007-08-19 22:22:54 +0000529 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000530 return false;
531}
Chris Lattner5c377c52001-10-14 23:29:15 +0000532
Chris Lattner1afcace2011-07-09 17:41:24 +0000533/// computeTypeMapping - Loop over all of the linked values to compute type
534/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
535/// we have two struct types 'Foo' but one got renamed when the module was
536/// loaded into the same LLVMContext.
537void ModuleLinker::computeTypeMapping() {
538 // Incorporate globals.
539 for (Module::global_iterator I = SrcM->global_begin(),
540 E = SrcM->global_end(); I != E; ++I) {
541 GlobalValue *DGV = getLinkedToGlobal(I);
542 if (DGV == 0) continue;
543
544 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
545 TypeMap.addTypeMapping(DGV->getType(), I->getType());
546 continue;
547 }
548
549 // Unify the element type of appending arrays.
550 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
551 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
552 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000553 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000554
555 // Incorporate functions.
556 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
557 if (GlobalValue *DGV = getLinkedToGlobal(I))
558 TypeMap.addTypeMapping(DGV->getType(), I->getType());
559 }
560
561 // Don't bother incorporating aliases, they aren't generally typed well.
562
563 // Now that we have discovered all of the type equivalences, get a body for
564 // any 'opaque' types in the dest module that are now resolved.
565 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000566}
567
Chris Lattner1afcace2011-07-09 17:41:24 +0000568/// linkAppendingVarProto - If there were any appending global variables, link
569/// them together now. Return true on error.
570bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
571 GlobalVariable *SrcGV) {
572
573 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
574 return emitError("Linking globals named '" + SrcGV->getName() +
575 "': can only link appending global with another appending global!");
576
577 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
578 ArrayType *SrcTy =
579 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
580 Type *EltTy = DstTy->getElementType();
581
582 // Check to see that they two arrays agree on type.
583 if (EltTy != SrcTy->getElementType())
584 return emitError("Appending variables with different element types!");
585 if (DstGV->isConstant() != SrcGV->isConstant())
586 return emitError("Appending variables linked with different const'ness!");
587
588 if (DstGV->getAlignment() != SrcGV->getAlignment())
589 return emitError(
590 "Appending variables with different alignment need to be linked!");
591
592 if (DstGV->getVisibility() != SrcGV->getVisibility())
593 return emitError(
594 "Appending variables with different visibility need to be linked!");
595
596 if (DstGV->getSection() != SrcGV->getSection())
597 return emitError(
598 "Appending variables with different section name need to be linked!");
599
600 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
601 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
602
603 // Create the new global variable.
604 GlobalVariable *NG =
605 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
606 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
607 DstGV->isThreadLocal(),
608 DstGV->getType()->getAddressSpace());
609
610 // Propagate alignment, visibility and section info.
611 CopyGVAttributes(NG, DstGV);
612
613 AppendingVarInfo AVI;
614 AVI.NewGV = NG;
615 AVI.DstInit = DstGV->getInitializer();
616 AVI.SrcInit = SrcGV->getInitializer();
617 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000618
Chris Lattner1afcace2011-07-09 17:41:24 +0000619 // Replace any uses of the two global variables with uses of the new
620 // global.
621 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000622
Chris Lattner1afcace2011-07-09 17:41:24 +0000623 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
624 DstGV->eraseFromParent();
625
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000626 // Track the source variable so we don't try to link it.
627 DoNotLinkFromSource.insert(SrcGV);
628
Chris Lattner1afcace2011-07-09 17:41:24 +0000629 return false;
630}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000631
Chris Lattner1afcace2011-07-09 17:41:24 +0000632/// linkGlobalProto - Loop through the global variables in the src module and
633/// merge them into the dest module.
634bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
635 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000636
Chris Lattner1afcace2011-07-09 17:41:24 +0000637 if (DGV) {
638 // Concatenation of appending linkage variables is magic and handled later.
639 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
640 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
641
642 // Determine whether linkage of these two globals follows the source
643 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000644 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
645 bool LinkFromSrc = false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000646 if (getLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000647 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000648
Chris Lattner1afcace2011-07-09 17:41:24 +0000649 // If we're not linking from the source, then keep the definition that we
650 // have.
651 if (!LinkFromSrc) {
652 // Special case for const propagation.
653 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
654 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
655 DGVar->setConstant(true);
656
657 // Set calculated linkage.
658 DGV->setLinkage(NewLinkage);
659
Chris Lattner6157e382008-07-14 07:23:24 +0000660 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000661 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
662
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000663 // Track the source global so that we don't attempt to copy it over when
664 // processing global initializers.
665 DoNotLinkFromSource.insert(SGV);
666
Chris Lattner1afcace2011-07-09 17:41:24 +0000667 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000668 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000669 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000670
671 // No linking to be performed or linking from the source: simply create an
672 // identical version of the symbol over in the dest module... the
673 // initializer will be filled in later by LinkGlobalInits.
674 GlobalVariable *NewDGV =
675 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
676 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
677 SGV->getName(), /*insertbefore*/0,
678 SGV->isThreadLocal(),
679 SGV->getType()->getAddressSpace());
680 // Propagate alignment, visibility and section info.
681 CopyGVAttributes(NewDGV, SGV);
682
683 if (DGV) {
684 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
685 DGV->eraseFromParent();
686 }
687
688 // Make sure to remember this mapping.
689 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000690 return false;
691}
692
Chris Lattner1afcace2011-07-09 17:41:24 +0000693/// linkFunctionProto - Link the function in the source module into the
694/// destination module if needed, setting up mapping information.
695bool ModuleLinker::linkFunctionProto(Function *SF) {
696 GlobalValue *DGV = getLinkedToGlobal(SF);
697
698 if (DGV) {
699 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
700 bool LinkFromSrc = false;
701 if (getLinkageResult(DGV, SF, NewLinkage, LinkFromSrc))
702 return true;
703
704 if (!LinkFromSrc) {
705 // Set calculated linkage
706 DGV->setLinkage(NewLinkage);
707
708 // Make sure to remember this mapping.
709 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
710
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000711 // Track the function from the source module so we don't attempt to remap
712 // it.
713 DoNotLinkFromSource.insert(SF);
714
Chris Lattner1afcace2011-07-09 17:41:24 +0000715 return false;
716 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000717 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000718
719 // If there is no linkage to be performed or we are linking from the source,
720 // bring SF over.
721 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
722 SF->getLinkage(), SF->getName(), DstM);
723 CopyGVAttributes(NewDF, SF);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000724
Chris Lattner1afcace2011-07-09 17:41:24 +0000725 if (DGV) {
726 // Any uses of DF need to change to NewDF, with cast.
727 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
728 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000729 } else {
730 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
731 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
732 SF->hasAvailableExternallyLinkage()) {
733 DoNotLinkFromSource.insert(SF);
734 LazilyLinkFunctions.push_back(SF);
735 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000736 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000737
738 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000739 return false;
740}
741
Chris Lattner1afcace2011-07-09 17:41:24 +0000742/// LinkAliasProto - Set up prototypes for any aliases that come over from the
743/// source module.
744bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
745 GlobalValue *DGV = getLinkedToGlobal(SGA);
746
747 if (DGV) {
748 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
749 bool LinkFromSrc = false;
750 if (getLinkageResult(DGV, SGA, NewLinkage, LinkFromSrc))
751 return true;
752
753 if (!LinkFromSrc) {
754 // Set calculated linkage.
755 DGV->setLinkage(NewLinkage);
756
757 // Make sure to remember this mapping.
758 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
759
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000760 // Track the alias from the source module so we don't attempt to remap it.
761 DoNotLinkFromSource.insert(SGA);
762
Chris Lattner1afcace2011-07-09 17:41:24 +0000763 return false;
764 }
765 }
766
767 // If there is no linkage to be performed or we're linking from the source,
768 // bring over SGA.
769 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
770 SGA->getLinkage(), SGA->getName(),
771 /*aliasee*/0, DstM);
772 CopyGVAttributes(NewDA, SGA);
Chris Lattner5c377c52001-10-14 23:29:15 +0000773
Chris Lattner1afcace2011-07-09 17:41:24 +0000774 if (DGV) {
775 // Any uses of DGV need to change to NewDA, with cast.
776 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
777 DGV->eraseFromParent();
778 }
779
780 ValueMap[SGA] = NewDA;
781 return false;
782}
783
784void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
785 // Merge the initializer.
786 SmallVector<Constant*, 16> Elements;
787 if (ConstantArray *I = dyn_cast<ConstantArray>(AVI.DstInit)) {
788 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
789 Elements.push_back(I->getOperand(i));
790 } else {
791 assert(isa<ConstantAggregateZero>(AVI.DstInit));
792 ArrayType *DstAT = cast<ArrayType>(AVI.DstInit->getType());
793 Type *EltTy = DstAT->getElementType();
794 Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy));
795 }
796
797 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
798 if (const ConstantArray *I = dyn_cast<ConstantArray>(SrcInit)) {
799 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
800 Elements.push_back(I->getOperand(i));
801 } else {
802 assert(isa<ConstantAggregateZero>(SrcInit));
803 ArrayType *SrcAT = cast<ArrayType>(SrcInit->getType());
804 Type *EltTy = SrcAT->getElementType();
805 Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy));
806 }
807 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
808 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
809}
810
811
812// linkGlobalInits - Update the initializers in the Dest module now that all
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000813// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000814void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000815 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000816 for (Module::const_global_iterator I = SrcM->global_begin(),
817 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000818
819 // Only process initialized GV's or ones not already in dest.
820 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000821
822 // Grab destination global variable.
823 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
824 // Figure out what the initializer looks like in the dest module.
825 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
826 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000827 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000828}
Chris Lattner5c377c52001-10-14 23:29:15 +0000829
Chris Lattner1afcace2011-07-09 17:41:24 +0000830// linkFunctionBody - Copy the source function over into the dest function and
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000831// fix up references to values. At this point we know that Dest is an external
832// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000833void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
834 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000835
Chris Lattner0033baf2004-11-16 17:12:38 +0000836 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000837 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000838 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000839 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000840 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000841
Chris Lattner1afcace2011-07-09 17:41:24 +0000842 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000843 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000844 }
845
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000846 if (Mode == Linker::DestroySource) {
847 // Splice the body of the source function into the dest function.
848 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
849
850 // At this point, all of the instructions and values of the function are now
851 // copied over. The only problem is that they are still referencing values in
852 // the Source function as operands. Loop through all of the operands of the
853 // functions and patch them up to point to the local versions.
854 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
855 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
856 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
857
858 } else {
859 // Clone the body of the function into the dest function.
860 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
861 CloneFunctionInto(Dst, Src, ValueMap, false, Returns);
862 }
863
Chris Lattner0033baf2004-11-16 17:12:38 +0000864 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000865 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
866 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000867 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000868
Chris Lattner5c377c52001-10-14 23:29:15 +0000869}
870
871
Chris Lattner1afcace2011-07-09 17:41:24 +0000872void ModuleLinker::linkAliasBodies() {
873 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000874 I != E; ++I) {
875 if (DoNotLinkFromSource.count(I))
876 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000877 if (Constant *Aliasee = I->getAliasee()) {
878 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
879 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000880 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000881 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000882}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000883
Chris Lattner1afcace2011-07-09 17:41:24 +0000884/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
885/// module.
886void ModuleLinker::linkNamedMDNodes() {
887 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
888 E = SrcM->named_metadata_end(); I != E; ++I) {
889 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
890 // Add Src elements into Dest node.
891 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
892 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
893 RF_None, &TypeMap));
894 }
895}
896
897bool ModuleLinker::run() {
898 assert(DstM && "Null Destination module");
899 assert(SrcM && "Null Source Module");
900
901 // Inherit the target data from the source module if the destination module
902 // doesn't have one already.
903 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
904 DstM->setDataLayout(SrcM->getDataLayout());
905
906 // Copy the target triple from the source to dest if the dest's is empty.
907 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
908 DstM->setTargetTriple(SrcM->getTargetTriple());
909
910 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
911 SrcM->getDataLayout() != DstM->getDataLayout())
912 errs() << "WARNING: Linking two modules of different data layouts!\n";
913 if (!SrcM->getTargetTriple().empty() &&
914 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
915 errs() << "WARNING: Linking two modules of different target triples: ";
916 if (!SrcM->getModuleIdentifier().empty())
917 errs() << SrcM->getModuleIdentifier() << ": ";
918 errs() << "'" << SrcM->getTargetTriple() << "' and '"
919 << DstM->getTargetTriple() << "'\n";
920 }
921
922 // Append the module inline asm string.
923 if (!SrcM->getModuleInlineAsm().empty()) {
924 if (DstM->getModuleInlineAsm().empty())
925 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
926 else
927 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
928 SrcM->getModuleInlineAsm());
929 }
930
931 // Update the destination module's dependent libraries list with the libraries
932 // from the source module. There's no opportunity for duplicates here as the
933 // Module ensures that duplicate insertions are discarded.
934 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
935 SI != SE; ++SI)
936 DstM->addLibrary(*SI);
937
938 // If the source library's module id is in the dependent library list of the
939 // destination library, remove it since that module is now linked in.
940 StringRef ModuleId = SrcM->getModuleIdentifier();
941 if (!ModuleId.empty())
942 DstM->removeLibrary(sys::path::stem(ModuleId));
Chris Lattner1afcace2011-07-09 17:41:24 +0000943
944 // Loop over all of the linked values to compute type mappings.
945 computeTypeMapping();
946
947 // Insert all of the globals in src into the DstM module... without linking
948 // initializers (which could refer to functions not yet mapped over).
949 for (Module::global_iterator I = SrcM->global_begin(),
950 E = SrcM->global_end(); I != E; ++I)
951 if (linkGlobalProto(I))
952 return true;
953
954 // Link the functions together between the two modules, without doing function
955 // bodies... this just adds external function prototypes to the DstM
956 // function... We do this so that when we begin processing function bodies,
957 // all of the global values that may be referenced are available in our
958 // ValueMap.
959 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
960 if (linkFunctionProto(I))
961 return true;
962
963 // If there were any aliases, link them now.
964 for (Module::alias_iterator I = SrcM->alias_begin(),
965 E = SrcM->alias_end(); I != E; ++I)
966 if (linkAliasProto(I))
967 return true;
968
969 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
970 linkAppendingVarInit(AppendingVars[i]);
971
972 // Update the initializers in the DstM module now that all globals that may
973 // be referenced are in DstM.
974 linkGlobalInits();
975
976 // Link in the function bodies that are defined in the source module into
977 // DstM.
978 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +0000979
980 // Skip if not linking from source.
981 if (DoNotLinkFromSource.count(SF)) continue;
982
983 // Skip if no body (function is external) or materialize.
984 if (SF->isDeclaration()) {
985 if (!SF->isMaterializable())
986 continue;
987 if (SF->Materialize(&ErrorMsg))
988 return true;
989 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000990
991 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
992 }
993
994 // Resolve all uses of aliases with aliasees.
995 linkAliasBodies();
996
Devang Patel211da8f2011-08-04 19:44:28 +0000997 // Remap all of the named mdnoes in Src into the DstM module. We do this
998 // after linking GlobalValues so that MDNodes that reference GlobalValues
999 // are properly remapped.
1000 linkNamedMDNodes();
1001
Tanya Lattner9af37a32011-11-02 00:24:56 +00001002 // Process vector of lazily linked in functions.
1003 bool LinkedInAnyFunctions;
1004 do {
1005 LinkedInAnyFunctions = false;
1006
1007 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1008 E = LazilyLinkFunctions.end(); I != E; ++I) {
1009 if (!*I)
1010 continue;
1011
1012 Function *SF = *I;
1013 Function *DF = cast<Function>(ValueMap[SF]);
1014
1015 if (!DF->use_empty()) {
1016
1017 // Materialize if necessary.
1018 if (SF->isDeclaration()) {
1019 if (!SF->isMaterializable())
1020 continue;
1021 if (SF->Materialize(&ErrorMsg))
1022 return true;
1023 }
1024
1025 // Link in function body.
1026 linkFunctionBody(DF, SF);
1027
1028 // "Remove" from vector by setting the element to 0.
1029 *I = 0;
1030
1031 // Set flag to indicate we may have more functions to lazily link in
1032 // since we linked in a function.
1033 LinkedInAnyFunctions = true;
1034 }
1035 }
1036 } while (LinkedInAnyFunctions);
1037
1038 // Remove any prototypes of functions that were not actually linked in.
1039 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1040 E = LazilyLinkFunctions.end(); I != E; ++I) {
1041 if (!*I)
1042 continue;
1043
1044 Function *SF = *I;
1045 Function *DF = cast<Function>(ValueMap[SF]);
1046 if (DF->use_empty())
1047 DF->eraseFromParent();
1048 }
1049
Chris Lattner1afcace2011-07-09 17:41:24 +00001050 // Now that all of the types from the source are used, resolve any structs
1051 // copied over to the dest that didn't exist there.
1052 TypeMap.linkDefinedTypeBodies();
1053
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001054 return false;
1055}
Chris Lattner52f7e902001-10-13 07:03:50 +00001056
Chris Lattner1afcace2011-07-09 17:41:24 +00001057//===----------------------------------------------------------------------===//
1058// LinkModules entrypoint.
1059//===----------------------------------------------------------------------===//
1060
Chris Lattner52f7e902001-10-13 07:03:50 +00001061// LinkModules - This function links two modules together, with the resulting
1062// left module modified to be the composite of the two input modules. If an
1063// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001064// the problem. Upon failure, the Dest module could be in a modified state, and
1065// shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001066bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1067 std::string *ErrorMsg) {
1068 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001069 if (TheLinker.run()) {
1070 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001071 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001072 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001073
Chris Lattner52f7e902001-10-13 07:03:50 +00001074 return false;
1075}