blob: 563aed5daa0c1c5e0fe9b30590a7432d3410abcc [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"
Rafael Espindola3ed88152012-01-05 23:02:01 +000020#include "llvm/ADT/Optional.h"
Chris Lattner74382b72009-08-23 22:45:37 +000021#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000022#include "llvm/Support/Path.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000023#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000024#include "llvm/Transforms/Utils/ValueMapper.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;
Chris Lattnerfc196f92008-06-16 23:06:51 +000050public:
Chris Lattner1afcace2011-07-09 17:41:24 +000051
52 /// 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
67private:
68 Type *getImpl(Type *T);
69 /// remapType - Implement the ValueMapTypeRemapper interface.
70 Type *remapType(Type *SrcTy) {
71 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000072 }
Chris Lattner1afcace2011-07-09 17:41:24 +000073
74 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000075};
76}
77
Chris Lattner1afcace2011-07-09 17:41:24 +000078void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
79 Type *&Entry = MappedTypes[SrcTy];
80 if (Entry) return;
81
82 if (DstTy == SrcTy) {
83 Entry = DstTy;
84 return;
85 }
86
87 // Check to see if these types are recursively isomorphic and establish a
88 // mapping between them if so.
89 if (!areTypesIsomorphic(DstTy, SrcTy)) {
90 // Oops, they aren't isomorphic. Just discard this request by rolling out
91 // any speculative mappings we've established.
92 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
93 MappedTypes.erase(SpeculativeTypes[i]);
94 }
95 SpeculativeTypes.clear();
96}
Chris Lattner62a81a12008-06-16 21:00:18 +000097
Chris Lattner1afcace2011-07-09 17:41:24 +000098/// areTypesIsomorphic - Recursively walk this pair of types, returning true
99/// if they are isomorphic, false if they are not.
100bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
101 // Two types with differing kinds are clearly not isomorphic.
102 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000103
Chris Lattner1afcace2011-07-09 17:41:24 +0000104 // If we have an entry in the MappedTypes table, then we have our answer.
105 Type *&Entry = MappedTypes[SrcTy];
106 if (Entry)
107 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000108
Chris Lattner1afcace2011-07-09 17:41:24 +0000109 // Two identical types are clearly isomorphic. Remember this
110 // non-speculatively.
111 if (DstTy == SrcTy) {
112 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000113 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000114 }
115
116 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000117
Chris Lattner1afcace2011-07-09 17:41:24 +0000118 // If this is an opaque struct type, special case it.
119 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
120 // Mapping an opaque type to any struct, just keep the dest struct.
121 if (SSTy->isOpaque()) {
122 Entry = DstTy;
123 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000124 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000125 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000126
Chris Lattner68910502011-12-20 00:03:52 +0000127 // Mapping a non-opaque source type to an opaque dest. If this is the first
128 // type that we're mapping onto this destination type then we succeed. Keep
129 // the dest, but fill it in later. This doesn't need to be speculative. If
130 // this is the second (different) type that we're trying to map onto the
131 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000132 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000133 // We can only map one source type onto the opaque destination type.
134 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
135 return false;
136 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000137 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000138 return true;
139 }
140 }
141
142 // If the number of subtypes disagree between the two types, then we fail.
143 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000144 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000145
146 // Fail if any of the extra properties (e.g. array size) of the type disagree.
147 if (isa<IntegerType>(DstTy))
148 return false; // bitwidth disagrees.
149 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
150 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
151 return false;
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000152
Chris Lattner1afcace2011-07-09 17:41:24 +0000153 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
154 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
155 return false;
156 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
157 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000158 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000159 DSTy->isPacked() != SSTy->isPacked())
160 return false;
161 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
162 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
163 return false;
164 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
165 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
166 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000167 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000168
169 // Otherwise, we speculate that these two types will line up and recursively
170 // check the subelements.
171 Entry = DstTy;
172 SpeculativeTypes.push_back(SrcTy);
173
174 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
175 if (!areTypesIsomorphic(DstTy->getContainedType(i),
176 SrcTy->getContainedType(i)))
177 return false;
178
179 // If everything seems to have lined up, then everything is great.
180 return true;
181}
182
183/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
184/// module from a type definition in the source module.
185void TypeMapTy::linkDefinedTypeBodies() {
186 SmallVector<Type*, 16> Elements;
187 SmallString<16> TmpName;
188
189 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000190 // entries to the SrcDefinitionsToResolve vector.
191 while (!SrcDefinitionsToResolve.empty()) {
192 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000193 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
194
195 // TypeMap is a many-to-one mapping, if there were multiple types that
196 // provide a body for DstSTy then previous iterations of this loop may have
197 // already handled it. Just ignore this case.
198 if (!DstSTy->isOpaque()) continue;
199 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
200
201 // Map the body of the source type over to a new body for the dest type.
202 Elements.resize(SrcSTy->getNumElements());
203 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
204 Elements[i] = getImpl(SrcSTy->getElementType(i));
205
206 DstSTy->setBody(Elements, SrcSTy->isPacked());
207
208 // If DstSTy has no name or has a longer name than STy, then viciously steal
209 // STy's name.
210 if (!SrcSTy->hasName()) continue;
211 StringRef SrcName = SrcSTy->getName();
212
213 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
214 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
215 SrcSTy->setName("");
216 DstSTy->setName(TmpName.str());
217 TmpName.clear();
218 }
219 }
Chris Lattner68910502011-12-20 00:03:52 +0000220
221 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000222}
223
224
225/// get - Return the mapped type to use for the specified input type from the
226/// source module.
227Type *TypeMapTy::get(Type *Ty) {
228 Type *Result = getImpl(Ty);
229
230 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner68910502011-12-20 00:03:52 +0000231 if (!SrcDefinitionsToResolve.empty())
Chris Lattner1afcace2011-07-09 17:41:24 +0000232 linkDefinedTypeBodies();
233 return Result;
234}
235
236/// getImpl - This is the recursive version of get().
237Type *TypeMapTy::getImpl(Type *Ty) {
238 // If we already have an entry for this type, return it.
239 Type **Entry = &MappedTypes[Ty];
240 if (*Entry) return *Entry;
241
242 // If this is not a named struct type, then just map all of the elements and
243 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000244 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000245 // If there are no element types to map, then the type is itself. This is
246 // true for the anonymous {} struct, things like 'float', integers, etc.
247 if (Ty->getNumContainedTypes() == 0)
248 return *Entry = Ty;
249
250 // Remap all of the elements, keeping track of whether any of them change.
251 bool AnyChange = false;
252 SmallVector<Type*, 4> ElementTypes;
253 ElementTypes.resize(Ty->getNumContainedTypes());
254 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
255 ElementTypes[i] = getImpl(Ty->getContainedType(i));
256 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
257 }
258
259 // If we found our type while recursively processing stuff, just use it.
260 Entry = &MappedTypes[Ty];
261 if (*Entry) return *Entry;
262
263 // If all of the element types mapped directly over, then the type is usable
264 // as-is.
265 if (!AnyChange)
266 return *Entry = Ty;
267
268 // Otherwise, rebuild a modified type.
269 switch (Ty->getTypeID()) {
270 default: assert(0 && "unknown derived type to remap");
271 case Type::ArrayTyID:
272 return *Entry = ArrayType::get(ElementTypes[0],
273 cast<ArrayType>(Ty)->getNumElements());
274 case Type::VectorTyID:
275 return *Entry = VectorType::get(ElementTypes[0],
276 cast<VectorType>(Ty)->getNumElements());
277 case Type::PointerTyID:
278 return *Entry = PointerType::get(ElementTypes[0],
279 cast<PointerType>(Ty)->getAddressSpace());
280 case Type::FunctionTyID:
281 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000282 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000283 cast<FunctionType>(Ty)->isVarArg());
284 case Type::StructTyID:
285 // Note that this is only reached for anonymous structs.
286 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
287 cast<StructType>(Ty)->isPacked());
288 }
289 }
290
291 // Otherwise, this is an unmapped named struct. If the struct can be directly
292 // mapped over, just use it as-is. This happens in a case when the linked-in
293 // module has something like:
294 // %T = type {%T*, i32}
295 // @GV = global %T* null
296 // where T does not exist at all in the destination module.
297 //
298 // The other case we watch for is when the type is not in the destination
299 // module, but that it has to be rebuilt because it refers to something that
300 // is already mapped. For example, if the destination module has:
301 // %A = type { i32 }
302 // and the source module has something like
303 // %A' = type { i32 }
304 // %B = type { %A'* }
305 // @GV = global %B* null
306 // then we want to create a new type: "%B = type { %A*}" and have it take the
307 // pristine "%B" name from the source module.
308 //
309 // To determine which case this is, we have to recursively walk the type graph
310 // speculating that we'll be able to reuse it unmodified. Only if this is
311 // safe would we map the entire thing over. Because this is an optimization,
312 // and is not required for the prettiness of the linked module, we just skip
313 // it and always rebuild a type here.
314 StructType *STy = cast<StructType>(Ty);
315
316 // If the type is opaque, we can just use it directly.
317 if (STy->isOpaque())
318 return *Entry = STy;
319
320 // Otherwise we create a new type and resolve its body later. This will be
321 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000322 SrcDefinitionsToResolve.push_back(STy);
323 StructType *DTy = StructType::create(STy->getContext());
324 DstResolvedOpaqueTypes.insert(DTy);
325 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000326}
327
328
329
330//===----------------------------------------------------------------------===//
331// ModuleLinker implementation.
332//===----------------------------------------------------------------------===//
333
334namespace {
335 /// ModuleLinker - This is an implementation class for the LinkModules
336 /// function, which is the entrypoint for this file.
337 class ModuleLinker {
338 Module *DstM, *SrcM;
339
340 TypeMapTy TypeMap;
341
342 /// ValueMap - Mapping of values from what they used to be in Src, to what
343 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
344 /// some overhead due to the use of Value handles which the Linker doesn't
345 /// actually need, but this allows us to reuse the ValueMapper code.
346 ValueToValueMapTy ValueMap;
347
348 struct AppendingVarInfo {
349 GlobalVariable *NewGV; // New aggregate global in dest module.
350 Constant *DstInit; // Old initializer from dest module.
351 Constant *SrcInit; // Old initializer from src module.
352 };
353
354 std::vector<AppendingVarInfo> AppendingVars;
355
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000356 unsigned Mode; // Mode to treat source module.
357
358 // Set of items not to link in from source.
359 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
360
Tanya Lattner9af37a32011-11-02 00:24:56 +0000361 // Vector of functions to lazily link in.
362 std::vector<Function*> LazilyLinkFunctions;
363
Chris Lattner1afcace2011-07-09 17:41:24 +0000364 public:
365 std::string ErrorMsg;
366
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000367 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
368 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000369
370 bool run();
371
372 private:
373 /// emitError - Helper method for setting a message and returning an error
374 /// code.
375 bool emitError(const Twine &Message) {
376 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000377 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000378 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000379
380 /// getLinkageResult - This analyzes the two global values and determines
381 /// what the result will look like in the destination module.
382 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000383 GlobalValue::LinkageTypes &LT,
384 GlobalValue::VisibilityTypes &Vis,
385 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000386
Chris Lattner1afcace2011-07-09 17:41:24 +0000387 /// getLinkedToGlobal - Given a global in the source module, return the
388 /// global in the destination module that is being linked to, if any.
389 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
390 // If the source has no name it can't link. If it has local linkage,
391 // there is no name match-up going on.
392 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
393 return 0;
394
395 // Otherwise see if we have a match in the destination module's symtab.
396 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
397 if (DGV == 0) return 0;
398
399 // If we found a global with the same name in the dest module, but it has
400 // internal linkage, we are really not doing any linkage here.
401 if (DGV->hasLocalLinkage())
402 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000403
Chris Lattner1afcace2011-07-09 17:41:24 +0000404 // Otherwise, we do in fact link to the destination global.
405 return DGV;
406 }
407
408 void computeTypeMapping();
409
410 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
411 bool linkGlobalProto(GlobalVariable *SrcGV);
412 bool linkFunctionProto(Function *SrcF);
413 bool linkAliasProto(GlobalAlias *SrcA);
414
415 void linkAppendingVarInit(const AppendingVarInfo &AVI);
416 void linkGlobalInits();
417 void linkFunctionBody(Function *Dst, Function *Src);
418 void linkAliasBodies();
419 void linkNamedMDNodes();
420 };
Chris Lattnere3092c92003-08-23 21:25:54 +0000421}
422
Chris Lattnere76c57a2003-08-22 06:07:12 +0000423
Chris Lattner2c236f32001-11-03 05:18:24 +0000424
Chris Lattner1afcace2011-07-09 17:41:24 +0000425/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000426/// in the symbol table. This is good for all clients except for us. Go
427/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000428static void forceRenaming(GlobalValue *GV, StringRef Name) {
429 // If the global doesn't force its name or if it already has the right name,
430 // there is nothing for us to do.
431 if (GV->hasLocalLinkage() || GV->getName() == Name)
432 return;
433
434 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000435
436 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000437 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000438 GV->takeName(ConflictGV);
439 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000440 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000441 } else {
442 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000443 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000444}
Reid Spencer8bef0372007-02-04 04:29:21 +0000445
Reid Spenceref9b9a72007-02-05 20:47:22 +0000446/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000447/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000448static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000449 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
450 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
451 DestGV->copyAttributesFrom(SrcGV);
452 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000453
454 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000455}
456
Rafael Espindola3ed88152012-01-05 23:02:01 +0000457static bool isLessConstraining(GlobalValue::VisibilityTypes a,
458 GlobalValue::VisibilityTypes b) {
459 if (a == GlobalValue::HiddenVisibility)
460 return false;
461 if (b == GlobalValue::HiddenVisibility)
462 return true;
463 if (a == GlobalValue::ProtectedVisibility)
464 return false;
465 if (b == GlobalValue::ProtectedVisibility)
466 return true;
467 return false;
468}
469
Chris Lattner1afcace2011-07-09 17:41:24 +0000470/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000471/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000472/// computes the resultant linkage type and visibility, computes whether the
473/// global in the source should be copied over to the destination (replacing
474/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000475bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000476 GlobalValue::LinkageTypes &LT,
477 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000478 bool &LinkFromSrc) {
479 assert(Dest && "Must have two globals being queried");
480 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000481 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000482
Peter Collingbourne88953162011-10-30 17:46:34 +0000483 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000484 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000485
486 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000487 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000488 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000489 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000490 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000491 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000492 LinkFromSrc = true;
493 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000494 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000495 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000496 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000497 LinkFromSrc = true;
498 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000499 } else {
500 LinkFromSrc = false;
501 LT = Dest->getLinkage();
502 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000503 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000504 // If Dest is external but Src is not:
505 LinkFromSrc = true;
506 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000507 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000508 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
509 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000510 if (Dest->hasExternalWeakLinkage() ||
511 Dest->hasAvailableExternallyLinkage() ||
512 (Dest->hasLinkOnceLinkage() &&
513 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000514 LinkFromSrc = true;
515 LT = Src->getLinkage();
516 } else {
517 LinkFromSrc = false;
518 LT = Dest->getLinkage();
519 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000520 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000521 // At this point we know that Src has External* or DLL* linkage.
522 if (Src->hasExternalWeakLinkage()) {
523 LinkFromSrc = false;
524 LT = Dest->getLinkage();
525 } else {
526 LinkFromSrc = true;
527 LT = GlobalValue::ExternalLinkage;
528 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000529 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000530 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
531 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
532 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
533 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000534 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000535 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000536 "': symbol multiply defined!");
537 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000538
Rafael Espindola3ed88152012-01-05 23:02:01 +0000539 // Compute the visibility. We follow the rules in the System V Application
540 // Binary Interface.
541 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
542 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000543 return false;
544}
Chris Lattner5c377c52001-10-14 23:29:15 +0000545
Chris Lattner1afcace2011-07-09 17:41:24 +0000546/// computeTypeMapping - Loop over all of the linked values to compute type
547/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
548/// we have two struct types 'Foo' but one got renamed when the module was
549/// loaded into the same LLVMContext.
550void ModuleLinker::computeTypeMapping() {
551 // Incorporate globals.
552 for (Module::global_iterator I = SrcM->global_begin(),
553 E = SrcM->global_end(); I != E; ++I) {
554 GlobalValue *DGV = getLinkedToGlobal(I);
555 if (DGV == 0) continue;
556
557 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
558 TypeMap.addTypeMapping(DGV->getType(), I->getType());
559 continue;
560 }
561
562 // Unify the element type of appending arrays.
563 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
564 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
565 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000566 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000567
568 // Incorporate functions.
569 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
570 if (GlobalValue *DGV = getLinkedToGlobal(I))
571 TypeMap.addTypeMapping(DGV->getType(), I->getType());
572 }
573
Chris Lattnerea933732011-12-20 00:12:26 +0000574 // Incorporate types by name, scanning all the types in the source module.
575 // At this point, the destination module may have a type "%foo = { i32 }" for
576 // example. When the source module got loaded into the same LLVMContext, if
577 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
578 // Though it isn't required for correctness, attempt to link these up to clean
579 // up the IR.
580 std::vector<StructType*> SrcStructTypes;
581 SrcM->findUsedStructTypes(SrcStructTypes);
582
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000583 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
584 SrcStructTypes.end());
585
Chris Lattnerea933732011-12-20 00:12:26 +0000586 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
587 StructType *ST = SrcStructTypes[i];
588 if (!ST->hasName()) continue;
589
590 // Check to see if there is a dot in the name followed by a digit.
591 size_t DotPos = ST->getName().rfind('.');
592 if (DotPos == 0 || DotPos == StringRef::npos ||
593 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
594 continue;
595
596 // Check to see if the destination module has a struct with the prefix name.
597 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000598 // Don't use it if this actually came from the source module. They're in
599 // the same LLVMContext after all.
600 if (!SrcStructTypesSet.count(DST))
601 TypeMap.addTypeMapping(DST, ST);
Chris Lattnerea933732011-12-20 00:12:26 +0000602 }
603
604
Chris Lattner1afcace2011-07-09 17:41:24 +0000605 // Don't bother incorporating aliases, they aren't generally typed well.
606
607 // Now that we have discovered all of the type equivalences, get a body for
608 // any 'opaque' types in the dest module that are now resolved.
609 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000610}
611
Chris Lattner1afcace2011-07-09 17:41:24 +0000612/// linkAppendingVarProto - If there were any appending global variables, link
613/// them together now. Return true on error.
614bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
615 GlobalVariable *SrcGV) {
616
617 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
618 return emitError("Linking globals named '" + SrcGV->getName() +
619 "': can only link appending global with another appending global!");
620
621 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
622 ArrayType *SrcTy =
623 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
624 Type *EltTy = DstTy->getElementType();
625
626 // Check to see that they two arrays agree on type.
627 if (EltTy != SrcTy->getElementType())
628 return emitError("Appending variables with different element types!");
629 if (DstGV->isConstant() != SrcGV->isConstant())
630 return emitError("Appending variables linked with different const'ness!");
631
632 if (DstGV->getAlignment() != SrcGV->getAlignment())
633 return emitError(
634 "Appending variables with different alignment need to be linked!");
635
636 if (DstGV->getVisibility() != SrcGV->getVisibility())
637 return emitError(
638 "Appending variables with different visibility need to be linked!");
639
640 if (DstGV->getSection() != SrcGV->getSection())
641 return emitError(
642 "Appending variables with different section name need to be linked!");
643
644 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
645 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
646
647 // Create the new global variable.
648 GlobalVariable *NG =
649 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
650 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
651 DstGV->isThreadLocal(),
652 DstGV->getType()->getAddressSpace());
653
654 // Propagate alignment, visibility and section info.
655 CopyGVAttributes(NG, DstGV);
656
657 AppendingVarInfo AVI;
658 AVI.NewGV = NG;
659 AVI.DstInit = DstGV->getInitializer();
660 AVI.SrcInit = SrcGV->getInitializer();
661 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000662
Chris Lattner1afcace2011-07-09 17:41:24 +0000663 // Replace any uses of the two global variables with uses of the new
664 // global.
665 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000666
Chris Lattner1afcace2011-07-09 17:41:24 +0000667 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
668 DstGV->eraseFromParent();
669
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000670 // Track the source variable so we don't try to link it.
671 DoNotLinkFromSource.insert(SrcGV);
672
Chris Lattner1afcace2011-07-09 17:41:24 +0000673 return false;
674}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000675
Chris Lattner1afcace2011-07-09 17:41:24 +0000676/// linkGlobalProto - Loop through the global variables in the src module and
677/// merge them into the dest module.
678bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
679 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000680 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000681
Chris Lattner1afcace2011-07-09 17:41:24 +0000682 if (DGV) {
683 // Concatenation of appending linkage variables is magic and handled later.
684 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
685 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
686
687 // Determine whether linkage of these two globals follows the source
688 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000689 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000690 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000691 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000692 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000693 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000694 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000695
Chris Lattner1afcace2011-07-09 17:41:24 +0000696 // If we're not linking from the source, then keep the definition that we
697 // have.
698 if (!LinkFromSrc) {
699 // Special case for const propagation.
700 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
701 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
702 DGVar->setConstant(true);
703
Rafael Espindola3ed88152012-01-05 23:02:01 +0000704 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000705 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000706 DGV->setVisibility(*NewVisibility);
707
Chris Lattner6157e382008-07-14 07:23:24 +0000708 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000709 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
710
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000711 // Track the source global so that we don't attempt to copy it over when
712 // processing global initializers.
713 DoNotLinkFromSource.insert(SGV);
714
Chris Lattner1afcace2011-07-09 17:41:24 +0000715 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000716 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000717 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000718
719 // No linking to be performed or linking from the source: simply create an
720 // identical version of the symbol over in the dest module... the
721 // initializer will be filled in later by LinkGlobalInits.
722 GlobalVariable *NewDGV =
723 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
724 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
725 SGV->getName(), /*insertbefore*/0,
726 SGV->isThreadLocal(),
727 SGV->getType()->getAddressSpace());
728 // Propagate alignment, visibility and section info.
729 CopyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000730 if (NewVisibility)
731 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000732
733 if (DGV) {
734 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
735 DGV->eraseFromParent();
736 }
737
738 // Make sure to remember this mapping.
739 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000740 return false;
741}
742
Chris Lattner1afcace2011-07-09 17:41:24 +0000743/// linkFunctionProto - Link the function in the source module into the
744/// destination module if needed, setting up mapping information.
745bool ModuleLinker::linkFunctionProto(Function *SF) {
746 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000747 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000748
749 if (DGV) {
750 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
751 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000752 GlobalValue::VisibilityTypes NV;
753 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000754 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000755 NewVisibility = NV;
756
Chris Lattner1afcace2011-07-09 17:41:24 +0000757 if (!LinkFromSrc) {
758 // Set calculated linkage
759 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000760 DGV->setVisibility(*NewVisibility);
761
Chris Lattner1afcace2011-07-09 17:41:24 +0000762 // Make sure to remember this mapping.
763 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
764
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000765 // Track the function from the source module so we don't attempt to remap
766 // it.
767 DoNotLinkFromSource.insert(SF);
768
Chris Lattner1afcace2011-07-09 17:41:24 +0000769 return false;
770 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000771 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000772
773 // If there is no linkage to be performed or we are linking from the source,
774 // bring SF over.
775 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
776 SF->getLinkage(), SF->getName(), DstM);
777 CopyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000778 if (NewVisibility)
779 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000780
Chris Lattner1afcace2011-07-09 17:41:24 +0000781 if (DGV) {
782 // Any uses of DF need to change to NewDF, with cast.
783 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
784 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000785 } else {
786 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
787 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
788 SF->hasAvailableExternallyLinkage()) {
789 DoNotLinkFromSource.insert(SF);
790 LazilyLinkFunctions.push_back(SF);
791 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000792 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000793
794 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000795 return false;
796}
797
Chris Lattner1afcace2011-07-09 17:41:24 +0000798/// LinkAliasProto - Set up prototypes for any aliases that come over from the
799/// source module.
800bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
801 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000802 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
803
Chris Lattner1afcace2011-07-09 17:41:24 +0000804 if (DGV) {
805 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000806 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000807 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000808 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000809 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000810 NewVisibility = NV;
811
Chris Lattner1afcace2011-07-09 17:41:24 +0000812 if (!LinkFromSrc) {
813 // Set calculated linkage.
814 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000815 DGV->setVisibility(*NewVisibility);
816
Chris Lattner1afcace2011-07-09 17:41:24 +0000817 // Make sure to remember this mapping.
818 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
819
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000820 // Track the alias from the source module so we don't attempt to remap it.
821 DoNotLinkFromSource.insert(SGA);
822
Chris Lattner1afcace2011-07-09 17:41:24 +0000823 return false;
824 }
825 }
826
827 // If there is no linkage to be performed or we're linking from the source,
828 // bring over SGA.
829 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
830 SGA->getLinkage(), SGA->getName(),
831 /*aliasee*/0, DstM);
832 CopyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000833 if (NewVisibility)
834 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000835
Chris Lattner1afcace2011-07-09 17:41:24 +0000836 if (DGV) {
837 // Any uses of DGV need to change to NewDA, with cast.
838 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
839 DGV->eraseFromParent();
840 }
841
842 ValueMap[SGA] = NewDA;
843 return false;
844}
845
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000846static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
847 if (ConstantArray *I = dyn_cast<ConstantArray>(C)) {
848 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
849 Dest.push_back(I->getOperand(i));
850 return;
851 }
852
853 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
854 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
855 Dest.push_back(CDS->getElementAsConstant(i));
856 return;
857 }
858
859 ConstantAggregateZero *CAZ = cast<ConstantAggregateZero>(C);
860 Dest.append(cast<ArrayType>(C->getType())->getNumElements(),
861 CAZ->getSequentialElement());
862}
863
Chris Lattner1afcace2011-07-09 17:41:24 +0000864void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
865 // Merge the initializer.
866 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000867 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000868
869 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000870 getArrayElements(SrcInit, Elements);
871
Chris Lattner1afcace2011-07-09 17:41:24 +0000872 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
873 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
874}
875
876
877// linkGlobalInits - Update the initializers in the Dest module now that all
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000878// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000879void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000880 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000881 for (Module::const_global_iterator I = SrcM->global_begin(),
882 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000883
884 // Only process initialized GV's or ones not already in dest.
885 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000886
887 // Grab destination global variable.
888 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
889 // Figure out what the initializer looks like in the dest module.
890 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
891 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000892 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000893}
Chris Lattner5c377c52001-10-14 23:29:15 +0000894
Chris Lattner1afcace2011-07-09 17:41:24 +0000895// linkFunctionBody - Copy the source function over into the dest function and
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000896// fix up references to values. At this point we know that Dest is an external
897// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000898void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
899 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000900
Chris Lattner0033baf2004-11-16 17:12:38 +0000901 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000902 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000903 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000904 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000905 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000906
Chris Lattner1afcace2011-07-09 17:41:24 +0000907 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000908 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000909 }
910
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000911 if (Mode == Linker::DestroySource) {
912 // Splice the body of the source function into the dest function.
913 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
914
915 // At this point, all of the instructions and values of the function are now
916 // copied over. The only problem is that they are still referencing values in
917 // the Source function as operands. Loop through all of the operands of the
918 // functions and patch them up to point to the local versions.
919 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
920 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
921 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
922
923 } else {
924 // Clone the body of the function into the dest function.
925 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000926 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000927 }
928
Chris Lattner0033baf2004-11-16 17:12:38 +0000929 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000930 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
931 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000932 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000933
Chris Lattner5c377c52001-10-14 23:29:15 +0000934}
935
936
Chris Lattner1afcace2011-07-09 17:41:24 +0000937void ModuleLinker::linkAliasBodies() {
938 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000939 I != E; ++I) {
940 if (DoNotLinkFromSource.count(I))
941 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000942 if (Constant *Aliasee = I->getAliasee()) {
943 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
944 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000945 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000946 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000947}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000948
Chris Lattner1afcace2011-07-09 17:41:24 +0000949/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
950/// module.
951void ModuleLinker::linkNamedMDNodes() {
952 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
953 E = SrcM->named_metadata_end(); I != E; ++I) {
954 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
955 // Add Src elements into Dest node.
956 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
957 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
958 RF_None, &TypeMap));
959 }
960}
961
962bool ModuleLinker::run() {
963 assert(DstM && "Null Destination module");
964 assert(SrcM && "Null Source Module");
965
966 // Inherit the target data from the source module if the destination module
967 // doesn't have one already.
968 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
969 DstM->setDataLayout(SrcM->getDataLayout());
970
971 // Copy the target triple from the source to dest if the dest's is empty.
972 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
973 DstM->setTargetTriple(SrcM->getTargetTriple());
974
975 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
976 SrcM->getDataLayout() != DstM->getDataLayout())
977 errs() << "WARNING: Linking two modules of different data layouts!\n";
978 if (!SrcM->getTargetTriple().empty() &&
979 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
980 errs() << "WARNING: Linking two modules of different target triples: ";
981 if (!SrcM->getModuleIdentifier().empty())
982 errs() << SrcM->getModuleIdentifier() << ": ";
983 errs() << "'" << SrcM->getTargetTriple() << "' and '"
984 << DstM->getTargetTriple() << "'\n";
985 }
986
987 // Append the module inline asm string.
988 if (!SrcM->getModuleInlineAsm().empty()) {
989 if (DstM->getModuleInlineAsm().empty())
990 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
991 else
992 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
993 SrcM->getModuleInlineAsm());
994 }
995
996 // Update the destination module's dependent libraries list with the libraries
997 // from the source module. There's no opportunity for duplicates here as the
998 // Module ensures that duplicate insertions are discarded.
999 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
1000 SI != SE; ++SI)
1001 DstM->addLibrary(*SI);
1002
1003 // If the source library's module id is in the dependent library list of the
1004 // destination library, remove it since that module is now linked in.
1005 StringRef ModuleId = SrcM->getModuleIdentifier();
1006 if (!ModuleId.empty())
1007 DstM->removeLibrary(sys::path::stem(ModuleId));
Chris Lattner1afcace2011-07-09 17:41:24 +00001008
1009 // Loop over all of the linked values to compute type mappings.
1010 computeTypeMapping();
1011
1012 // Insert all of the globals in src into the DstM module... without linking
1013 // initializers (which could refer to functions not yet mapped over).
1014 for (Module::global_iterator I = SrcM->global_begin(),
1015 E = SrcM->global_end(); I != E; ++I)
1016 if (linkGlobalProto(I))
1017 return true;
1018
1019 // Link the functions together between the two modules, without doing function
1020 // bodies... this just adds external function prototypes to the DstM
1021 // function... We do this so that when we begin processing function bodies,
1022 // all of the global values that may be referenced are available in our
1023 // ValueMap.
1024 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1025 if (linkFunctionProto(I))
1026 return true;
1027
1028 // If there were any aliases, link them now.
1029 for (Module::alias_iterator I = SrcM->alias_begin(),
1030 E = SrcM->alias_end(); I != E; ++I)
1031 if (linkAliasProto(I))
1032 return true;
1033
1034 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1035 linkAppendingVarInit(AppendingVars[i]);
1036
1037 // Update the initializers in the DstM module now that all globals that may
1038 // be referenced are in DstM.
1039 linkGlobalInits();
1040
1041 // Link in the function bodies that are defined in the source module into
1042 // DstM.
1043 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001044
1045 // Skip if not linking from source.
1046 if (DoNotLinkFromSource.count(SF)) continue;
1047
1048 // Skip if no body (function is external) or materialize.
1049 if (SF->isDeclaration()) {
1050 if (!SF->isMaterializable())
1051 continue;
1052 if (SF->Materialize(&ErrorMsg))
1053 return true;
1054 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001055
1056 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1057 }
1058
1059 // Resolve all uses of aliases with aliasees.
1060 linkAliasBodies();
1061
Devang Patel211da8f2011-08-04 19:44:28 +00001062 // Remap all of the named mdnoes in Src into the DstM module. We do this
1063 // after linking GlobalValues so that MDNodes that reference GlobalValues
1064 // are properly remapped.
1065 linkNamedMDNodes();
1066
Tanya Lattner9af37a32011-11-02 00:24:56 +00001067 // Process vector of lazily linked in functions.
1068 bool LinkedInAnyFunctions;
1069 do {
1070 LinkedInAnyFunctions = false;
1071
1072 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1073 E = LazilyLinkFunctions.end(); I != E; ++I) {
1074 if (!*I)
1075 continue;
1076
1077 Function *SF = *I;
1078 Function *DF = cast<Function>(ValueMap[SF]);
1079
1080 if (!DF->use_empty()) {
1081
1082 // Materialize if necessary.
1083 if (SF->isDeclaration()) {
1084 if (!SF->isMaterializable())
1085 continue;
1086 if (SF->Materialize(&ErrorMsg))
1087 return true;
1088 }
1089
1090 // Link in function body.
1091 linkFunctionBody(DF, SF);
1092
1093 // "Remove" from vector by setting the element to 0.
1094 *I = 0;
1095
1096 // Set flag to indicate we may have more functions to lazily link in
1097 // since we linked in a function.
1098 LinkedInAnyFunctions = true;
1099 }
1100 }
1101 } while (LinkedInAnyFunctions);
1102
1103 // Remove any prototypes of functions that were not actually linked in.
1104 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1105 E = LazilyLinkFunctions.end(); I != E; ++I) {
1106 if (!*I)
1107 continue;
1108
1109 Function *SF = *I;
1110 Function *DF = cast<Function>(ValueMap[SF]);
1111 if (DF->use_empty())
1112 DF->eraseFromParent();
1113 }
1114
Chris Lattner1afcace2011-07-09 17:41:24 +00001115 // Now that all of the types from the source are used, resolve any structs
1116 // copied over to the dest that didn't exist there.
1117 TypeMap.linkDefinedTypeBodies();
1118
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001119 return false;
1120}
Chris Lattner52f7e902001-10-13 07:03:50 +00001121
Chris Lattner1afcace2011-07-09 17:41:24 +00001122//===----------------------------------------------------------------------===//
1123// LinkModules entrypoint.
1124//===----------------------------------------------------------------------===//
1125
Chris Lattner52f7e902001-10-13 07:03:50 +00001126// LinkModules - This function links two modules together, with the resulting
1127// left module modified to be the composite of the two input modules. If an
1128// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001129// the problem. Upon failure, the Dest module could be in a modified state, and
1130// shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001131bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1132 std::string *ErrorMsg) {
1133 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001134 if (TheLinker.run()) {
1135 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001136 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001137 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001138
Chris Lattner52f7e902001-10-13 07:03:50 +00001139 return false;
1140}