blob: b7ab5dff5d6db16d24b6e5622da6a6bec5f5838e [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//
12// Specifically, this:
Chris Lattner8d2de8a2001-10-15 03:12:52 +000013// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000015// * Merges functions between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +000016//
17//===----------------------------------------------------------------------===//
18
Reid Spencer7cc371a2004-11-14 23:27:04 +000019#include "llvm/Linker.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Owen Andersonc9ab7bf2009-07-07 21:07:14 +000022#include "llvm/LLVMContext.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000023#include "llvm/Module.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000024#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000025#include "llvm/ValueSymbolTable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000026#include "llvm/Instructions.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000027#include "llvm/Assembly/Writer.h"
Bill Wendling41edad72006-11-27 10:09:12 +000028#include "llvm/Support/Streams.h"
Reid Spencer57a0efa2004-09-11 04:25:17 +000029#include "llvm/System/Path.h"
Chris Lattner62a81a12008-06-16 21:00:18 +000030#include "llvm/ADT/DenseMap.h"
Bill Wendling1a097e32006-12-07 23:41:45 +000031#include <sstream>
Chris Lattnerf7703df2004-01-09 06:12:26 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattner5c377c52001-10-14 23:29:15 +000034// Error - Simple wrapper function to conditionally assign to E and return true.
35// This just makes error return conditions a little bit simpler...
Chris Lattner8166e6e2003-05-13 21:33:43 +000036static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000037 if (E) *E = Message;
38 return true;
39}
40
John Criswell700867b2003-11-04 15:22:26 +000041// Function: ResolveTypes()
42//
43// Description:
44// Attempt to link the two specified types together.
45//
46// Inputs:
47// DestTy - The type to which we wish to resolve.
48// SrcTy - The original type which we want to resolve.
John Criswell700867b2003-11-04 15:22:26 +000049//
50// Outputs:
51// DestST - The symbol table in which the new type should be placed.
52//
53// Return value:
54// true - There is an error and the types cannot yet be linked.
55// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000056//
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000057static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000058 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000059 assert(DestTy && SrcTy && "Can't handle null types");
Chris Lattnere76c57a2003-08-22 06:07:12 +000060
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000061 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
62 // Type _is_ in module, just opaque...
63 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
64 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
65 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
66 } else {
67 return true; // Cannot link types... not-equal and neither is opaque.
Chris Lattner4c00e532003-05-15 16:30:55 +000068 }
69 return false;
70}
71
Chris Lattner62a81a12008-06-16 21:00:18 +000072/// LinkerTypeMap - This implements a map of types that is stable
73/// even if types are resolved/refined to other types. This is not a general
74/// purpose map, it is specific to the linker's use.
75namespace {
76class LinkerTypeMap : public AbstractTypeUser {
77 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
78 TheMapTy TheMap;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000079
Chris Lattnerfc196f92008-06-16 23:06:51 +000080 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
81 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
82public:
83 LinkerTypeMap() {}
84 ~LinkerTypeMap() {
Chris Lattner62a81a12008-06-16 21:00:18 +000085 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
86 E = TheMap.end(); I != E; ++I)
87 I->first->removeAbstractTypeUser(this);
88 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000089
Chris Lattner62a81a12008-06-16 21:00:18 +000090 /// lookup - Return the value for the specified type or null if it doesn't
91 /// exist.
92 const Type *lookup(const Type *Ty) const {
93 TheMapTy::const_iterator I = TheMap.find(Ty);
94 if (I != TheMap.end()) return I->second;
95 return 0;
96 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000097
Chris Lattner62a81a12008-06-16 21:00:18 +000098 /// erase - Remove the specified type, returning true if it was in the set.
99 bool erase(const Type *Ty) {
100 if (!TheMap.erase(Ty))
101 return false;
102 if (Ty->isAbstract())
103 Ty->removeAbstractTypeUser(this);
104 return true;
105 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000106
Chris Lattner62a81a12008-06-16 21:00:18 +0000107 /// insert - This returns true if the pointer was new to the set, false if it
108 /// was already in the set.
109 bool insert(const Type *Src, const Type *Dst) {
Dan Gohman6b345ee2008-07-07 17:46:23 +0000110 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
Chris Lattner62a81a12008-06-16 21:00:18 +0000111 return false; // Already in map.
112 if (Src->isAbstract())
113 Src->addAbstractTypeUser(this);
114 return true;
115 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000116
Chris Lattner62a81a12008-06-16 21:00:18 +0000117protected:
118 /// refineAbstractType - The callback method invoked when an abstract type is
119 /// resolved to another type. An object must override this method to update
120 /// its internal state to reference NewType instead of OldType.
121 ///
122 virtual void refineAbstractType(const DerivedType *OldTy,
123 const Type *NewTy) {
124 TheMapTy::iterator I = TheMap.find(OldTy);
125 const Type *DstTy = I->second;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000126
Chris Lattner62a81a12008-06-16 21:00:18 +0000127 TheMap.erase(I);
128 if (OldTy->isAbstract())
129 OldTy->removeAbstractTypeUser(this);
130
131 // Don't reinsert into the map if the key is concrete now.
132 if (NewTy->isAbstract())
133 insert(NewTy, DstTy);
134 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000135
Chris Lattner62a81a12008-06-16 21:00:18 +0000136 /// The other case which AbstractTypeUsers must be aware of is when a type
137 /// makes the transition from being abstract (where it has clients on it's
138 /// AbstractTypeUsers list) to concrete (where it does not). This method
139 /// notifies ATU's when this occurs for a type.
140 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
141 TheMap.erase(AbsTy);
142 AbsTy->removeAbstractTypeUser(this);
143 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000144
Chris Lattner62a81a12008-06-16 21:00:18 +0000145 // for debugging...
146 virtual void dump() const {
147 cerr << "AbstractTypeSet!\n";
148 }
149};
150}
151
152
Chris Lattnere76c57a2003-08-22 06:07:12 +0000153// RecursiveResolveTypes - This is just like ResolveTypes, except that it
154// recurses down into derived types, merging the used types if the parent types
155// are compatible.
Chris Lattnera4477f92008-06-16 21:17:12 +0000156static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner62a81a12008-06-16 21:00:18 +0000157 LinkerTypeMap &Pointers) {
Chris Lattnera4477f92008-06-16 21:17:12 +0000158 if (DstTy == SrcTy) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +0000159
Chris Lattnere76c57a2003-08-22 06:07:12 +0000160 // If we found our opaque type, resolve it now!
Chris Lattnera4477f92008-06-16 21:17:12 +0000161 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
162 return ResolveTypes(DstTy, SrcTy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000163
Chris Lattnere76c57a2003-08-22 06:07:12 +0000164 // Two types cannot be resolved together if they are of different primitive
165 // type. For example, we cannot resolve an int to a float.
Chris Lattnera4477f92008-06-16 21:17:12 +0000166 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000167
Chris Lattner56539652008-06-16 20:03:01 +0000168 // If neither type is abstract, then they really are just different types.
Chris Lattnera4477f92008-06-16 21:17:12 +0000169 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattner56539652008-06-16 20:03:01 +0000170 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000171
Chris Lattnere76c57a2003-08-22 06:07:12 +0000172 // Otherwise, resolve the used type used by this derived type...
Chris Lattnera4477f92008-06-16 21:17:12 +0000173 switch (DstTy->getTypeID()) {
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000174 default:
175 return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000176 case Type::FunctionTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000177 const FunctionType *DstFT = cast<FunctionType>(DstTy);
178 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000179 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
180 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000181 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000182
Chris Lattnera4477f92008-06-16 21:17:12 +0000183 // Use TypeHolder's so recursive resolution won't break us.
184 PATypeHolder ST(SrcFT), DT(DstFT);
185 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
186 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
187 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000188 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000189 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000190 return false;
191 }
192 case Type::StructTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000193 const StructType *DstST = cast<StructType>(DstTy);
194 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000195 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000196 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000197
Chris Lattnera4477f92008-06-16 21:17:12 +0000198 PATypeHolder ST(SrcST), DT(DstST);
199 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
200 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
201 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000202 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000203 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000204 return false;
205 }
206 case Type::ArrayTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000207 const ArrayType *DAT = cast<ArrayType>(DstTy);
208 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000209 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000210 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000211 Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000212 }
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000213 case Type::VectorTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000214 const VectorType *DVT = cast<VectorType>(DstTy);
215 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000216 if (DVT->getNumElements() != SVT->getNumElements()) return true;
217 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
218 Pointers);
219 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000220 case Type::PointerTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000221 const PointerType *DstPT = cast<PointerType>(DstTy);
222 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000223
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000224 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
225 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000226
Chris Lattnere3092c92003-08-23 21:25:54 +0000227 // If this is a pointer type, check to see if we have already seen it. If
228 // so, we are in a recursive branch. Cut off the search now. We cannot use
229 // an associative container for this search, because the type pointers (keys
Chris Lattner62a81a12008-06-16 21:00:18 +0000230 // in the container) change whenever types get resolved.
231 if (SrcPT->isAbstract())
232 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
233 return ExistingDestTy != DstPT;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000234
Chris Lattner62a81a12008-06-16 21:00:18 +0000235 if (DstPT->isAbstract())
236 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
237 return ExistingSrcTy != SrcPT;
Chris Lattnere3092c92003-08-23 21:25:54 +0000238 // Otherwise, add the current pointers to the vector to stop recursion on
239 // this pair.
Chris Lattner62a81a12008-06-16 21:00:18 +0000240 if (DstPT->isAbstract())
241 Pointers.insert(DstPT, SrcPT);
242 if (SrcPT->isAbstract())
243 Pointers.insert(SrcPT, DstPT);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000244
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000245 return RecursiveResolveTypesI(DstPT->getElementType(),
246 SrcPT->getElementType(), Pointers);
Chris Lattnere3092c92003-08-23 21:25:54 +0000247 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000248 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000249}
250
Chris Lattnera4477f92008-06-16 21:17:12 +0000251static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner62a81a12008-06-16 21:00:18 +0000252 LinkerTypeMap PointerTypes;
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000253 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Chris Lattnere3092c92003-08-23 21:25:54 +0000254}
255
Chris Lattnere76c57a2003-08-22 06:07:12 +0000256
Chris Lattner2c236f32001-11-03 05:18:24 +0000257// LinkTypes - Go through the symbol table of the Src module and see if any
258// types are named in the src module that are not named in the Dst module.
259// Make sure there are no type name conflicts.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000260static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000261 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
262 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000263
264 // Look for a type plane for Type's...
Reid Spencer78d033e2007-01-06 07:24:44 +0000265 TypeSymbolTable::const_iterator TI = SrcST->begin();
266 TypeSymbolTable::const_iterator TE = SrcST->end();
Reid Spencer567bc2c2004-05-25 08:52:20 +0000267 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000268
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000269 // Some types cannot be resolved immediately because they depend on other
270 // types being resolved to each other first. This contains a list of types we
271 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000272 std::vector<std::string> DelayedTypesToResolve;
273
Reid Spencer567bc2c2004-05-25 08:52:20 +0000274 for ( ; TI != TE; ++TI ) {
275 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000276 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000277
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000278 // Check to see if this type name is already in the dest module.
Reid Spencer78d033e2007-01-06 07:24:44 +0000279 Type *Entry = DestST->lookup(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000280
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000281 // If the name is just in the source module, bring it over to the dest.
282 if (Entry == 0) {
283 if (!Name.empty())
284 DestST->insert(Name, const_cast<Type*>(RHS));
285 } else if (ResolveTypes(Entry, RHS)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000286 // They look different, save the types 'till later to resolve.
287 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000288 }
289 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000290
291 // Iteratively resolve types while we can...
292 while (!DelayedTypesToResolve.empty()) {
293 // Loop over all of the types, attempting to resolve them if possible...
294 unsigned OldSize = DelayedTypesToResolve.size();
295
Chris Lattnere76c57a2003-08-22 06:07:12 +0000296 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000297 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
298 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000299 Type *T1 = SrcST->lookup(Name);
300 Type *T2 = DestST->lookup(Name);
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000301 if (!ResolveTypes(T2, T1)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000302 // We are making progress!
303 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
304 --i;
305 }
306 }
307
308 // Did we not eliminate any types?
309 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000310 // Attempt to resolve subelements of types. This allows us to merge these
311 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000312 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
313 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnera4477f92008-06-16 21:17:12 +0000314 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000315 // We are making progress!
316 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000317
Chris Lattnere76c57a2003-08-22 06:07:12 +0000318 // Go back to the main loop, perhaps we can resolve directly by name
319 // now...
320 break;
321 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000322 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000323
324 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000325 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000326 // Remove the symbol name from the destination.
327 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000328 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000329 }
330 }
331
332
Chris Lattner2c236f32001-11-03 05:18:24 +0000333 return false;
334}
335
Chris Lattner0bb87572008-07-14 05:52:33 +0000336#ifndef NDEBUG
Chris Lattner5c2d3352003-01-30 19:53:34 +0000337static void PrintMap(const std::map<const Value*, Value*> &M) {
338 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000339 I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000340 cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000341 I->first->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000342 cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000343 I->second->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000344 cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000345 }
346}
Chris Lattner0bb87572008-07-14 05:52:33 +0000347#endif
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000348
349
Reid Spencer619f0242007-02-04 04:43:17 +0000350// RemapOperand - Use ValueMap to convert constants from one module to another.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000351static Value *RemapOperand(const Value *In,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000352 std::map<const Value*, Value*> &ValueMap,
353 LLVMContext &Context) {
Chris Lattner0033baf2004-11-16 17:12:38 +0000354 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000355 if (I != ValueMap.end())
Reid Spenceref9b9a72007-02-05 20:47:22 +0000356 return I->second;
Chris Lattner5c377c52001-10-14 23:29:15 +0000357
Reid Spencer619f0242007-02-04 04:43:17 +0000358 // Check to see if it's a constant that we are interested in transforming.
Chris Lattner620fd682006-06-01 19:14:22 +0000359 Value *Result = 0;
Chris Lattner18961502002-06-25 16:12:52 +0000360 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000361 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000362 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
Chris Lattner0033baf2004-11-16 17:12:38 +0000363 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000364
Chris Lattner18961502002-06-25 16:12:52 +0000365 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000366 std::vector<Constant*> Operands(CPA->getNumOperands());
367 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000368 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap,
369 Context));
370 Result =
371 Context.getConstantArray(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000372 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000373 std::vector<Constant*> Operands(CPS->getNumOperands());
374 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000375 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap,
376 Context));
377 Result =
378 Context.getConstantStruct(cast<StructType>(CPS->getType()), Operands);
Chris Lattnerb976e662004-10-16 18:08:06 +0000379 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000380 Result = const_cast<Constant*>(CPV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000381 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
Chris Lattnera88eb922006-01-19 23:15:58 +0000382 std::vector<Constant*> Operands(CP->getNumOperands());
383 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000384 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap,
385 Context));
386 Result = Context.getConstantVector(Operands);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000387 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner27d67212006-07-14 22:21:31 +0000388 std::vector<Constant*> Ops;
389 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000390 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap,
391 Context)));
Chris Lattner27d67212006-07-14 22:21:31 +0000392 Result = CE->getWithOperands(Ops);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000393 } else {
Chris Lattner0bb87572008-07-14 05:52:33 +0000394 assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000395 assert(0 && "Unknown type of derived type constant value!");
396 }
Chris Lattner620fd682006-06-01 19:14:22 +0000397 } else if (isa<InlineAsm>(In)) {
398 Result = const_cast<Value*>(In);
399 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000400
Reid Spencer619f0242007-02-04 04:43:17 +0000401 // Cache the mapping in our local map structure
Chris Lattner620fd682006-06-01 19:14:22 +0000402 if (Result) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000403 ValueMap[In] = Result;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000404 return Result;
405 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000406
Chris Lattner0bb87572008-07-14 05:52:33 +0000407#ifndef NDEBUG
Bill Wendlinge8156192006-12-07 01:30:32 +0000408 cerr << "LinkModules ValueMap: \n";
Chris Lattner0033baf2004-11-16 17:12:38 +0000409 PrintMap(ValueMap);
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000410
Bill Wendlinge8156192006-12-07 01:30:32 +0000411 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000412 assert(0 && "Couldn't remap value!");
Chris Lattner0bb87572008-07-14 05:52:33 +0000413#endif
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000414 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000415}
416
Reid Spencer8bef0372007-02-04 04:29:21 +0000417/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
418/// in the symbol table. This is good for all clients except for us. Go
419/// through the trouble to force this back.
Chris Lattnerc0036282004-08-04 07:05:54 +0000420static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
421 assert(GV->getName() != Name && "Can't force rename to self");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000422 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
Chris Lattnerc0036282004-08-04 07:05:54 +0000423
424 // If there is a conflict, rename the conflict.
Chris Lattner33f29492007-02-11 00:39:38 +0000425 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000426 assert(ConflictGV->hasLocalLinkage() &&
Reid Spenceref9b9a72007-02-05 20:47:22 +0000427 "Not conflicting with a static global, should link instead!");
Chris Lattner33f29492007-02-11 00:39:38 +0000428 GV->takeName(ConflictGV);
429 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Reid Spenceref9b9a72007-02-05 20:47:22 +0000430 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000431 } else {
432 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000433 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000434}
Reid Spencer8bef0372007-02-04 04:29:21 +0000435
Reid Spenceref9b9a72007-02-05 20:47:22 +0000436/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000437/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000438static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000439 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
440 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
441 DestGV->copyAttributesFrom(SrcGV);
442 DestGV->setAlignment(Alignment);
Chris Lattnerc0036282004-08-04 07:05:54 +0000443}
444
Chris Lattneraee38ea2004-12-03 22:18:41 +0000445/// GetLinkageResult - This analyzes the two global values and determines what
446/// the result will look like in the destination module. In particular, it
447/// computes the resultant linkage type, computes whether the global in the
448/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000449/// one), and computes whether this linkage is an error or not. It also performs
450/// visibility checks: we cannot link together two symbols with different
451/// visibilities.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000452static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Chris Lattneraee38ea2004-12-03 22:18:41 +0000453 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
454 std::string *Err) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000455 assert((!Dest || !Src->hasLocalLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000456 "If Src has internal linkage, Dest shouldn't be set!");
457 if (!Dest) {
458 // Linking something to nothing.
459 LinkFromSrc = true;
460 LT = Src->getLinkage();
Reid Spencer5cbf9852007-01-30 20:08:39 +0000461 } else if (Src->isDeclaration()) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000462 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000463 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000464 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000465 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000466 if (Dest->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000467 LinkFromSrc = true;
468 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000469 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000470 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000471 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000472 LinkFromSrc = true;
473 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000474 } else {
475 LinkFromSrc = false;
476 LT = Dest->getLinkage();
477 }
Reid Spencer5cbf9852007-01-30 20:08:39 +0000478 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000479 // If Dest is external but Src is not:
480 LinkFromSrc = true;
481 LT = Src->getLinkage();
482 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
483 if (Src->getLinkage() != Dest->getLinkage())
484 return Error(Err, "Linking globals named '" + Src->getName() +
485 "': can only link appending global with another appending global!");
486 LinkFromSrc = true; // Special cased.
487 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000488 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000489 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
490 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000491 if (Dest->hasExternalWeakLinkage() ||
492 Dest->hasAvailableExternallyLinkage() ||
493 (Dest->hasLinkOnceLinkage() &&
494 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000495 LinkFromSrc = true;
496 LT = Src->getLinkage();
497 } else {
498 LinkFromSrc = false;
499 LT = Dest->getLinkage();
500 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000501 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000502 // At this point we know that Src has External* or DLL* linkage.
503 if (Src->hasExternalWeakLinkage()) {
504 LinkFromSrc = false;
505 LT = Dest->getLinkage();
506 } else {
507 LinkFromSrc = true;
508 LT = GlobalValue::ExternalLinkage;
509 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000510 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000511 assert((Dest->hasExternalLinkage() ||
512 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000513 Dest->hasDLLExportLinkage() ||
514 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000515 (Src->hasExternalLinkage() ||
516 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000517 Src->hasDLLExportLinkage() ||
518 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000519 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000520 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000521 "': symbol multiply defined!");
522 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000523
524 // Check visibility
525 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattner97f8b092007-08-19 22:22:54 +0000526 if (!Src->isDeclaration() && !Dest->isDeclaration())
527 return Error(Err, "Linking globals named '" + Src->getName() +
528 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000529 return false;
530}
Chris Lattner5c377c52001-10-14 23:29:15 +0000531
532// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000533// them into the dest module.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000534static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000535 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000536 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000537 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000538 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000539 LLVMContext &Context = Dest->getContext();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000540
Chris Lattner5c377c52001-10-14 23:29:15 +0000541 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner0bb87572008-07-14 05:52:33 +0000542 for (Module::const_global_iterator I = Src->global_begin(),
543 E = Src->global_end(); I != E; ++I) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000544 const GlobalVariable *SGV = I;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000545 GlobalValue *DGV = 0;
546
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000547 // Check to see if may have to link the global with the global, alias or
548 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000549 if (SGV->hasName() && !SGV->hasLocalLinkage())
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000550 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getNameStart(),
551 SGV->getNameEnd()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000552
Chris Lattnerae1132d2008-07-14 06:52:19 +0000553 // If we found a global with the same name in the dest module, but it has
554 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000555 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000556 DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000557
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000558 // If types don't agree due to opaque types, try to resolve them.
559 if (DGV && DGV->getType() != SGV->getType())
560 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000561
Dan Gohmanc3183292007-10-08 15:13:30 +0000562 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
563 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000564 "Global must either be external or have an initializer!");
565
Chris Lattnerb324bd72006-11-09 05:18:12 +0000566 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
567 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000568 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
569 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000570
Chris Lattner6157e382008-07-14 07:23:24 +0000571 if (DGV == 0) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000572 // No linking to be performed, simply create an identical version of the
573 // symbol over in the dest module... the initializer will be filled in
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000574 // later by LinkGlobalInits.
Chris Lattner2719bac2003-04-21 21:15:04 +0000575 GlobalVariable *NewDGV =
576 new GlobalVariable(SGV->getType()->getElementType(),
577 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000578 SGV->getName(), Dest, false,
579 SGV->getType()->getAddressSpace());
Reid Spencer471feac2007-02-04 04:30:33 +0000580 // Propagate alignment, visibility and section info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000581 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000582
Chris Lattner2719bac2003-04-21 21:15:04 +0000583 // If the LLVM runtime renamed the global, but it is an externally visible
584 // symbol, DGV must be an existing global with internal linkage. Rename
585 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000586 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
Chris Lattnerc0036282004-08-04 07:05:54 +0000587 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000588
Chris Lattner6157e382008-07-14 07:23:24 +0000589 // Make sure to remember this mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000590 ValueMap[SGV] = NewDGV;
591
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000592 // Keep track that this is an appending variable.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000593 if (SGV->hasAppendingLinkage())
Chris Lattner8166e6e2003-05-13 21:33:43 +0000594 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000595 continue;
596 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000597
Chris Lattner6157e382008-07-14 07:23:24 +0000598 // If the visibilities of the symbols disagree and the destination is a
599 // prototype, take the visibility of its input.
600 if (DGV->isDeclaration())
601 DGV->setVisibility(SGV->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000602
Chris Lattner6157e382008-07-14 07:23:24 +0000603 if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000604 // No linking is performed yet. Just insert a new copy of the global, and
605 // keep track of the fact that it is an appending variable in the
606 // AppendingVars map. The name is cleared out so that no linkage is
607 // performed.
608 GlobalVariable *NewDGV =
609 new GlobalVariable(SGV->getType()->getElementType(),
610 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000611 "", Dest, false,
612 SGV->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +0000613
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000614 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000615 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000616 // Propagate alignment, section and visibility info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000617 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000618
Chris Lattner8166e6e2003-05-13 21:33:43 +0000619 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000620 ValueMap[SGV] = NewDGV;
Chris Lattner8166e6e2003-05-13 21:33:43 +0000621
622 // Keep track that this is an appending variable...
623 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000624 continue;
625 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000626
Chris Lattner6157e382008-07-14 07:23:24 +0000627 if (LinkFromSrc) {
628 if (isa<GlobalAlias>(DGV))
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000629 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
630 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000631
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000632 // If the types don't match, and if we are to link from the source, nuke
633 // DGV and create a new one of the appropriate type. Note that the thing
634 // we are replacing may be a function (if a prototype, weak, etc) or a
635 // global variable.
636 GlobalVariable *NewDGV =
Chris Lattner6157e382008-07-14 07:23:24 +0000637 new GlobalVariable(SGV->getType()->getElementType(), SGV->isConstant(),
638 NewLinkage, /*init*/0, DGV->getName(), Dest, false,
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000639 SGV->getType()->getAddressSpace());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000640
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000641 // Propagate alignment, section, and visibility info.
642 CopyGVAttributes(NewDGV, SGV);
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000643 DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDGV,
644 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000645
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000646 // DGV will conflict with NewDGV because they both had the same
647 // name. We must erase this now so ForceRenaming doesn't assert
648 // because DGV might not have internal linkage.
649 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
650 Var->eraseFromParent();
651 else
652 cast<Function>(DGV)->eraseFromParent();
653 DGV = NewDGV;
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000654
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000655 // If the symbol table renamed the global, but it is an externally visible
656 // symbol, DGV must be an existing global with internal linkage. Rename.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000657 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000658 ForceRenaming(NewDGV, SGV->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000659
Chris Lattner6157e382008-07-14 07:23:24 +0000660 // Inherit const as appropriate.
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000661 NewDGV->setConstant(SGV->isConstant());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000662
Chris Lattner6157e382008-07-14 07:23:24 +0000663 // Make sure to remember this mapping.
664 ValueMap[SGV] = NewDGV;
665 continue;
Chris Lattner5c377c52001-10-14 23:29:15 +0000666 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000667
Chris Lattner6157e382008-07-14 07:23:24 +0000668 // Not "link from source", keep the one in the DestModule and remap the
669 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000670
Chris Lattner6157e382008-07-14 07:23:24 +0000671 // Special case for const propagation.
672 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
673 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
674 DGVar->setConstant(true);
675
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000676 // SGV is global, but DGV is alias.
677 if (isa<GlobalAlias>(DGV)) {
678 // The only valid mappings are:
679 // - SGV is external declaration, which is effectively a no-op.
680 // - SGV is weak, when we just need to throw SGV out.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000681 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000682 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
683 "': symbol multiple defined");
684 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000685
Chris Lattner6157e382008-07-14 07:23:24 +0000686 // Set calculated linkage
687 DGV->setLinkage(NewLinkage);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000688
Chris Lattner6157e382008-07-14 07:23:24 +0000689 // Make sure to remember this mapping...
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000690 ValueMap[SGV] = Context.getConstantExprBitCast(DGV, SGV->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000691 }
692 return false;
693}
694
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000695static GlobalValue::LinkageTypes
696CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000697 GlobalValue::LinkageTypes SL = SGV->getLinkage();
698 GlobalValue::LinkageTypes DL = DGV->getLinkage();
699 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000700 return GlobalValue::ExternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +0000701 else if (SL == GlobalValue::WeakAnyLinkage ||
702 DL == GlobalValue::WeakAnyLinkage)
703 return GlobalValue::WeakAnyLinkage;
704 else if (SL == GlobalValue::WeakODRLinkage ||
705 DL == GlobalValue::WeakODRLinkage)
706 return GlobalValue::WeakODRLinkage;
707 else if (SL == GlobalValue::InternalLinkage &&
708 DL == GlobalValue::InternalLinkage)
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000709 return GlobalValue::InternalLinkage;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000710 else {
Duncan Sands667d4b82009-03-07 15:45:40 +0000711 assert (SL == GlobalValue::PrivateLinkage &&
712 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
Rafael Espindolabb46f522009-01-15 20:18:42 +0000713 return GlobalValue::PrivateLinkage;
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000714 }
715}
716
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000717// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000718// dest module. We're assuming, that all functions/global variables were already
719// linked in.
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000720static bool LinkAlias(Module *Dest, const Module *Src,
721 std::map<const Value*, Value*> &ValueMap,
722 std::string *Err) {
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000723 LLVMContext &Context = Dest->getContext();
724
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000725 // Loop over all alias in the src module
726 for (Module::const_alias_iterator I = Src->alias_begin(),
727 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000728 const GlobalAlias *SGA = I;
729 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
730 GlobalAlias *NewGA = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000731
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000732 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000733 // of SAliasee in Dest.
Ted Kremenek58d5e052008-03-09 18:32:50 +0000734 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
735 assert(VMI != ValueMap.end() && "Aliasee not linked");
736 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000737 GlobalValue* DGV = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000738
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000739 // Try to find something 'similar' to SGA in destination module.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000740 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000741 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000742
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000743 // If types don't agree due to opaque types, try to resolve them.
744 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000745 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000746 }
747
Rafael Espindolabb46f522009-01-15 20:18:42 +0000748 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000749 DGV = Dest->getGlobalVariable(SGA->getName());
750
751 // If types don't agree due to opaque types, try to resolve them.
752 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000753 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000754 }
755
Rafael Espindolabb46f522009-01-15 20:18:42 +0000756 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000757 DGV = Dest->getFunction(SGA->getName());
758
759 // If types don't agree due to opaque types, try to resolve them.
760 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000761 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000762 }
763
764 // No linking to be performed on internal stuff.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000765 if (DGV && DGV->hasLocalLinkage())
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000766 DGV = NULL;
767
768 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
769 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000770 // globals are already linked we just need query ValueMap to find the
771 // mapping.
772 if (DAliasee == DGA->getAliasedGlobal()) {
773 // This is just two copies of the same alias. Propagate linkage, if
774 // necessary.
775 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
776
777 NewGA = DGA;
778 // Proceed to 'common' steps
779 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000780 return Error(Err, "Alias Collision on '" + SGA->getName()+
781 "': aliases have different aliasees");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000782 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000783 // The only allowed way is to link alias with external declaration or weak
784 // symbol..
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000785 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000786 // But only if aliasee is global too...
787 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000788 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
789 "': aliasee is not global variable");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000790
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000791 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
792 SGA->getName(), DAliasee, Dest);
793 CopyGVAttributes(NewGA, SGA);
794
795 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000796 if (SGA->getType() != DGVar->getType())
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000797 DGVar->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000798 DGVar->getType()));
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000799 else
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000800 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000801
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000802 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000803 // name. We must erase this now so ForceRenaming doesn't assert
804 // because DGV might not have internal linkage.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000805 DGVar->eraseFromParent();
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000806
807 // Proceed to 'common' steps
808 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000809 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
810 "': symbol multiple defined");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000811 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000812 // The only allowed way is to link alias with external declaration or weak
813 // symbol...
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000814 if (DF->isDeclaration() || DF->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000815 // But only if aliasee is function too...
816 if (!isa<Function>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000817 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
818 "': aliasee is not function");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000819
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000820 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
821 SGA->getName(), DAliasee, Dest);
822 CopyGVAttributes(NewGA, SGA);
823
824 // Any uses of DF need to change to NewGA, with cast, if needed.
825 if (SGA->getType() != DF->getType())
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000826 DF->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000827 DF->getType()));
828 else
829 DF->replaceAllUsesWith(NewGA);
830
831 // DF will conflict with NewGA because they both had the same
832 // name. We must erase this now so ForceRenaming doesn't assert
833 // because DF might not have internal linkage.
834 DF->eraseFromParent();
835
836 // Proceed to 'common' steps
837 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000838 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
839 "': symbol multiple defined");
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000840 } else {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000841 // No linking to be performed, simply create an identical version of the
842 // alias over in the dest module...
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000843
844 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
845 SGA->getName(), DAliasee, Dest);
846 CopyGVAttributes(NewGA, SGA);
847
848 // Proceed to 'common' steps
849 }
850
851 assert(NewGA && "No alias was created in destination module!");
852
Anton Korobeynikovb8cdaf72008-03-10 22:36:35 +0000853 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000854 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000855 if (NewGA->getName() != SGA->getName() &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000856 !NewGA->hasLocalLinkage())
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000857 ForceRenaming(NewGA, SGA->getName());
858
859 // Remember this mapping so uses in the source module get remapped
860 // later by RemapOperand.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000861 ValueMap[SGA] = NewGA;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000862 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000863
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000864 return false;
865}
866
Chris Lattner5c377c52001-10-14 23:29:15 +0000867
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000868// LinkGlobalInits - Update the initializers in the Dest module now that all
869// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000870static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000871 std::map<const Value*, Value*> &ValueMap,
872 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000873 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000874 for (Module::const_global_iterator I = Src->global_begin(),
875 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000876 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000877
878 if (SGV->hasInitializer()) { // Only process initialized GV's
879 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000880 Constant *SInit =
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000881 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap,
882 Dest->getContext()));
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000883 // Grab destination global variable or alias.
884 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000885
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000886 // If dest if global variable, check that initializers match.
887 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
888 if (DGVar->hasInitializer()) {
889 if (SGV->hasExternalLinkage()) {
890 if (DGVar->getInitializer() != SInit)
891 return Error(Err, "Global Variable Collision on '" +
892 SGV->getName() +
893 "': global variables have different initializers");
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000894 } else if (DGVar->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000895 // Nothing is required, mapped values will take the new global
896 // automatically.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000897 } else if (SGV->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000898 // Nothing is required, mapped values will take the new global
899 // automatically.
900 } else if (DGVar->hasAppendingLinkage()) {
901 assert(0 && "Appending linkage unimplemented!");
902 } else {
903 assert(0 && "Unknown linkage!");
904 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000905 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000906 // Copy the initializer over now...
907 DGVar->setInitializer(SInit);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000908 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000909 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000910 // Destination is alias, the only valid situation is when source is
911 // weak. Also, note, that we already checked linkage in LinkGlobals(),
912 // thus we assert here.
913 // FIXME: Should we weaken this assumption, 'dereference' alias and
914 // check for initializer of aliasee?
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000915 assert(SGV->isWeakForLinker());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000916 }
917 }
918 }
919 return false;
920}
Chris Lattner5c377c52001-10-14 23:29:15 +0000921
Chris Lattner79df7c02002-03-26 18:01:55 +0000922// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000923// without doing function bodies... this just adds external function prototypes
924// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000925//
Chris Lattner79df7c02002-03-26 18:01:55 +0000926static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000927 std::map<const Value*, Value*> &ValueMap,
928 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000929 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000930 LLVMContext &Context = Dest->getContext();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000931
Reid Spencer619f0242007-02-04 04:43:17 +0000932 // Loop over all of the functions in the src module, mapping them over
Chris Lattner5c377c52001-10-14 23:29:15 +0000933 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000934 const Function *SF = I; // SrcFunction
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000935 GlobalValue *DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000936
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000937 // Check to see if may have to link the function with the global, alias or
938 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000939 if (SF->hasName() && !SF->hasLocalLinkage())
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000940 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getNameStart(),
941 SF->getNameEnd()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000942
Chris Lattnerae1132d2008-07-14 06:52:19 +0000943 // If we found a global with the same name in the dest module, but it has
944 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000945 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000946 DGV = 0;
947
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000948 // If types don't agree due to opaque types, try to resolve them.
949 if (DGV && DGV->getType() != SF->getType())
950 RecursiveResolveTypes(SF->getType(), DGV->getType());
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000951
Chris Lattner6157e382008-07-14 07:23:24 +0000952 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
953 bool LinkFromSrc = false;
954 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
955 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000956
Chris Lattner82468492008-06-09 07:36:11 +0000957 // If there is no linkage to be performed, just bring over SF without
958 // modifying it.
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000959 if (DGV == 0) {
Chris Lattner82468492008-06-09 07:36:11 +0000960 // Function does not already exist, simply insert an function signature
961 // identical to SF into the dest module.
962 Function *NewDF = Function::Create(SF->getFunctionType(),
963 SF->getLinkage(),
964 SF->getName(), Dest);
965 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000966
Chris Lattner82468492008-06-09 07:36:11 +0000967 // If the LLVM runtime renamed the function, but it is an externally
968 // visible symbol, DF must be an existing function with internal linkage.
969 // Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000970 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
Chris Lattner82468492008-06-09 07:36:11 +0000971 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000972
Chris Lattner82468492008-06-09 07:36:11 +0000973 // ... and remember this mapping...
974 ValueMap[SF] = NewDF;
975 continue;
Chris Lattner6157e382008-07-14 07:23:24 +0000976 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000977
Chris Lattner6157e382008-07-14 07:23:24 +0000978 // If the visibilities of the symbols disagree and the destination is a
979 // prototype, take the visibility of its input.
980 if (DGV->isDeclaration())
981 DGV->setVisibility(SF->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000982
Chris Lattner6157e382008-07-14 07:23:24 +0000983 if (LinkFromSrc) {
984 if (isa<GlobalAlias>(DGV))
985 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
986 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000987
Chris Lattner6157e382008-07-14 07:23:24 +0000988 // We have a definition of the same name but different type in the
989 // source module. Copy the prototype to the destination and replace
990 // uses of the destination's prototype with the new prototype.
991 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
992 SF->getName(), Dest);
993 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000994
Chris Lattner6157e382008-07-14 07:23:24 +0000995 // Any uses of DF need to change to NewDF, with cast
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000996 DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDF,
997 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000998
Chris Lattner6157e382008-07-14 07:23:24 +0000999 // DF will conflict with NewDF because they both had the same. We must
1000 // erase this now so ForceRenaming doesn't assert because DF might
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001001 // not have internal linkage.
Chris Lattner6157e382008-07-14 07:23:24 +00001002 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1003 Var->eraseFromParent();
1004 else
1005 cast<Function>(DGV)->eraseFromParent();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001006
Chris Lattner6157e382008-07-14 07:23:24 +00001007 // If the symbol table renamed the function, but it is an externally
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001008 // visible symbol, DF must be an existing function with internal
Chris Lattner6157e382008-07-14 07:23:24 +00001009 // linkage. Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001010 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
Chris Lattner6157e382008-07-14 07:23:24 +00001011 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001012
Chris Lattner6157e382008-07-14 07:23:24 +00001013 // Remember this mapping so uses in the source module get remapped
1014 // later by RemapOperand.
1015 ValueMap[SF] = NewDF;
1016 continue;
1017 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001018
Chris Lattner6157e382008-07-14 07:23:24 +00001019 // Not "link from source", keep the one in the DestModule and remap the
1020 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001021
Chris Lattner6157e382008-07-14 07:23:24 +00001022 if (isa<GlobalAlias>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +00001023 // The only valid mappings are:
1024 // - SF is external declaration, which is effectively a no-op.
1025 // - SF is weak, when we just need to throw SF out.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +00001026 if (!SF->isDeclaration() && !SF->isWeakForLinker())
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +00001027 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1028 "': symbol multiple defined");
Chris Lattner82468492008-06-09 07:36:11 +00001029 }
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +00001030
Chris Lattner6157e382008-07-14 07:23:24 +00001031 // Set calculated linkage
1032 DGV->setLinkage(NewLinkage);
Chris Lattner5c377c52001-10-14 23:29:15 +00001033
Chris Lattner6157e382008-07-14 07:23:24 +00001034 // Make sure to remember this mapping.
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001035 ValueMap[SF] = Context.getConstantExprBitCast(DGV, SF->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +00001036 }
1037 return false;
1038}
1039
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001040// LinkFunctionBody - Copy the source function over into the dest function and
1041// fix up references to values. At this point we know that Dest is an external
1042// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001043static bool LinkFunctionBody(Function *Dest, Function *Src,
Reid Spenceref9b9a72007-02-05 20:47:22 +00001044 std::map<const Value*, Value*> &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001045 std::string *Err) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001046 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +00001047
Chris Lattner0033baf2004-11-16 17:12:38 +00001048 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +00001049 Function::arg_iterator DI = Dest->arg_begin();
1050 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +00001051 I != E; ++I, ++DI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +00001052 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +00001053
1054 // Add a mapping to our local map
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +00001055 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +00001056 }
1057
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001058 // Splice the body of the source function into the dest function.
1059 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +00001060
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001061 // At this point, all of the instructions and values of the function are now
1062 // copied over. The only problem is that they are still referencing values in
1063 // the Source function as operands. Loop through all of the operands of the
1064 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +00001065 //
Chris Lattner18961502002-06-25 16:12:52 +00001066 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1067 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1068 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +00001069 OI != OE; ++OI)
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001070 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001071 *OI = RemapOperand(*OI, ValueMap, *Dest->getContext());
Chris Lattner0033baf2004-11-16 17:12:38 +00001072
1073 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +00001074 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1075 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +00001076 ValueMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +00001077
1078 return false;
1079}
1080
1081
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001082// LinkFunctionBodies - Link in the function bodies that are defined in the
1083// source module into the DestModule. This consists basically of copying the
1084// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001085static bool LinkFunctionBodies(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001086 std::map<const Value*, Value*> &ValueMap,
1087 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +00001088
Reid Spencer8bef0372007-02-04 04:29:21 +00001089 // Loop over all of the functions in the src module, mapping them over as we
1090 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001091 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer619f0242007-02-04 04:43:17 +00001092 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001093 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +00001094
Chris Lattner18961502002-06-25 16:12:52 +00001095 // DF not external SF external?
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001096 if (DF && DF->isDeclaration())
Chris Lattner35956552003-10-27 16:39:39 +00001097 // Only provide the function body if there isn't one already.
1098 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1099 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +00001100 }
Chris Lattner5c377c52001-10-14 23:29:15 +00001101 }
1102 return false;
1103}
1104
Chris Lattner8166e6e2003-05-13 21:33:43 +00001105// LinkAppendingVars - If there were any appending global variables, link them
1106// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001107static bool LinkAppendingVars(Module *M,
1108 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1109 std::string *ErrorMsg) {
1110 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +00001111
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001112 LLVMContext &Context = M->getContext();
1113
Chris Lattner8166e6e2003-05-13 21:33:43 +00001114 // Loop over the multimap of appending vars, processing any variables with the
1115 // same name, forming a new appending global variable with both of the
1116 // initializers merged together, then rewrite references to the old variables
1117 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001118 std::vector<Constant*> Inits;
1119 while (AppendingVars.size() > 1) {
1120 // Get the first two elements in the map...
1121 std::multimap<std::string,
1122 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1123
1124 // If the first two elements are for different names, there is no pair...
1125 // Otherwise there is a pair, so link them together...
1126 if (First->first == Second->first) {
1127 GlobalVariable *G1 = First->second, *G2 = Second->second;
1128 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1129 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +00001130
Chris Lattner8166e6e2003-05-13 21:33:43 +00001131 // Check to see that they two arrays agree on type...
1132 if (T1->getElementType() != T2->getElementType())
1133 return Error(ErrorMsg,
1134 "Appending variables with different element types need to be linked!");
1135 if (G1->isConstant() != G2->isConstant())
1136 return Error(ErrorMsg,
1137 "Appending variables linked with different const'ness!");
1138
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001139 if (G1->getAlignment() != G2->getAlignment())
1140 return Error(ErrorMsg,
1141 "Appending variables with different alignment need to be linked!");
1142
1143 if (G1->getVisibility() != G2->getVisibility())
1144 return Error(ErrorMsg,
1145 "Appending variables with different visibility need to be linked!");
1146
1147 if (G1->getSection() != G2->getSection())
1148 return Error(ErrorMsg,
1149 "Appending variables with different section name need to be linked!");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001150
Chris Lattner8166e6e2003-05-13 21:33:43 +00001151 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001152 ArrayType *NewType = Context.getArrayType(T1->getElementType(),
1153 NewSize);
Chris Lattner8166e6e2003-05-13 21:33:43 +00001154
Chris Lattnered74a4e2005-12-06 17:30:58 +00001155 G1->setName(""); // Clear G1's name in case of a conflict!
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001156
Chris Lattner8166e6e2003-05-13 21:33:43 +00001157 // Create the new global variable...
1158 GlobalVariable *NG =
1159 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
Chris Lattnera534b0f2008-06-27 03:10:24 +00001160 /*init*/0, First->first, M, G1->isThreadLocal(),
1161 G1->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +00001162
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001163 // Propagate alignment, visibility and section info.
1164 CopyGVAttributes(NG, G1);
1165
Chris Lattner8166e6e2003-05-13 21:33:43 +00001166 // Merge the initializer...
1167 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +00001168 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1169 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001170 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001171 } else {
1172 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001173 Constant *CV = Context.getNullValue(T1->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001174 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1175 Inits.push_back(CV);
1176 }
1177 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1178 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001179 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001180 } else {
1181 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001182 Constant *CV = Context.getNullValue(T2->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001183 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1184 Inits.push_back(CV);
1185 }
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001186 NG->setInitializer(Context.getConstantArray(NewType, Inits));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001187 Inits.clear();
1188
1189 // Replace any uses of the two global variables with uses of the new
1190 // global...
1191
1192 // FIXME: This should rewrite simple/straight-forward uses such as
1193 // getelementptr instructions to not use the Cast!
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001194 G1->replaceAllUsesWith(Context.getConstantExprBitCast(NG,
1195 G1->getType()));
1196 G2->replaceAllUsesWith(Context.getConstantExprBitCast(NG,
1197 G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001198
1199 // Remove the two globals from the module now...
1200 M->getGlobalList().erase(G1);
1201 M->getGlobalList().erase(G2);
1202
1203 // Put the new global into the AppendingVars map so that we can handle
1204 // linking of more than two vars...
1205 Second->second = NG;
1206 }
1207 AppendingVars.erase(First);
1208 }
1209
1210 return false;
1211}
Chris Lattner52f7e902001-10-13 07:03:50 +00001212
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001213static bool ResolveAliases(Module *Dest) {
1214 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov52419572008-03-11 22:51:09 +00001215 I != E; ++I)
Anton Korobeynikov19e861a2008-09-09 20:05:04 +00001216 if (const GlobalValue *GV = I->resolveAliasedGlobal())
Anton Korobeynikov832b2a92008-09-09 18:23:48 +00001217 if (GV != I && !GV->isDeclaration())
Anton Korobeynikov52419572008-03-11 22:51:09 +00001218 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001219
1220 return false;
1221}
Chris Lattner52f7e902001-10-13 07:03:50 +00001222
1223// LinkModules - This function links two modules together, with the resulting
1224// left module modified to be the composite of the two input modules. If an
1225// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001226// the problem. Upon failure, the Dest module could be in a modified state, and
1227// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +00001228bool
Reid Spencer0ba9e212004-12-13 03:00:16 +00001229Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +00001230 assert(Dest != 0 && "Invalid Destination module");
1231 assert(Src != 0 && "Invalid Source Module");
1232
Chris Lattnerc36357c2007-01-29 00:21:34 +00001233 if (Dest->getDataLayout().empty()) {
1234 if (!Src->getDataLayout().empty()) {
Chris Lattnerec9bfdc2007-01-29 02:18:13 +00001235 Dest->setDataLayout(Src->getDataLayout());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001236 } else {
1237 std::string DataLayout;
Reid Spencer26f23852007-01-26 08:11:39 +00001238
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001239 if (Dest->getEndianness() == Module::AnyEndianness) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001240 if (Src->getEndianness() == Module::BigEndian)
1241 DataLayout.append("E");
1242 else if (Src->getEndianness() == Module::LittleEndian)
1243 DataLayout.append("e");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001244 }
1245
1246 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001247 if (Src->getPointerSize() == Module::Pointer64)
1248 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1249 else if (Src->getPointerSize() == Module::Pointer32)
1250 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001251 }
Chris Lattnerc36357c2007-01-29 00:21:34 +00001252 Dest->setDataLayout(DataLayout);
1253 }
1254 }
1255
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001256 // Copy the target triple from the source to dest if the dest's is empty.
Chris Lattnerc36357c2007-01-29 00:21:34 +00001257 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
Chris Lattner152f19a2004-12-10 20:26:15 +00001258 Dest->setTargetTriple(Src->getTargetTriple());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001259
Chris Lattnerc36357c2007-01-29 00:21:34 +00001260 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1261 Src->getDataLayout() != Dest->getDataLayout())
Reid Spencer26f23852007-01-26 08:11:39 +00001262 cerr << "WARNING: Linking two modules of different data layouts!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +00001263 if (!Src->getTargetTriple().empty() &&
1264 Dest->getTargetTriple() != Src->getTargetTriple())
Bill Wendlinge8156192006-12-07 01:30:32 +00001265 cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001266
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001267 // Append the module inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001268 if (!Src->getModuleInlineAsm().empty()) {
1269 if (Dest->getModuleInlineAsm().empty())
1270 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001271 else
Chris Lattner66316012006-01-24 04:14:29 +00001272 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1273 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001274 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001275
Reid Spencer719012d2004-11-25 09:29:44 +00001276 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +00001277 // from the source module. There's no opportunity for duplicates here as the
1278 // Module ensures that duplicate insertions are discarded.
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001279 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001280 SI != SE; ++SI)
Reid Spencer57a0efa2004-09-11 04:25:17 +00001281 Dest->addLibrary(*SI);
Reid Spencer57a0efa2004-09-11 04:25:17 +00001282
Chris Lattner2c236f32001-11-03 05:18:24 +00001283 // LinkTypes - Go through the symbol table of the Src module and see if any
1284 // types are named in the src module that are not named in the Dst module.
1285 // Make sure there are no type name conflicts.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001286 if (LinkTypes(Dest, Src, ErrorMsg))
Reid Spencer619f0242007-02-04 04:43:17 +00001287 return true;
Chris Lattner2c236f32001-11-03 05:18:24 +00001288
Chris Lattner5c377c52001-10-14 23:29:15 +00001289 // ValueMap - Mapping of values from what they used to be in Src, to what they
1290 // are now in Dest.
Chris Lattner5c2d3352003-01-30 19:53:34 +00001291 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +00001292
Chris Lattner8166e6e2003-05-13 21:33:43 +00001293 // AppendingVars - Keep track of global variables in the destination module
1294 // with appending linkage. After the module is linked together, they are
1295 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001296 std::multimap<std::string, GlobalVariable *> AppendingVars;
Chris Lattner11273152006-06-16 01:24:04 +00001297 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1298 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +00001299 // Add all of the appending globals already in the Dest module to
1300 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +00001301 if (I->hasAppendingLinkage())
1302 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner5a837de2004-08-04 07:44:58 +00001303 }
1304
Chris Lattner8166e6e2003-05-13 21:33:43 +00001305 // Insert all of the globals in src into the Dest module... without linking
1306 // initializers (which could refer to functions not yet mapped over).
Reid Spenceref9b9a72007-02-05 20:47:22 +00001307 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001308 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001309
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001310 // Link the functions together between the two modules, without doing function
1311 // bodies... this just adds external function prototypes to the Dest
1312 // function... We do this so that when we begin processing function bodies,
1313 // all of the global values that may be referenced are available in our
1314 // ValueMap.
Reid Spenceref9b9a72007-02-05 20:47:22 +00001315 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001316 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001317
Anton Korobeynikov4fb28732008-03-05 15:27:21 +00001318 // If there were any alias, link them now. We really need to do this now,
1319 // because all of the aliases that may be referenced need to be available in
1320 // ValueMap
1321 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1322
Chris Lattner6cdf1972002-07-18 00:13:08 +00001323 // Update the initializers in the Dest module now that all globals that may
1324 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +00001325 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1326
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001327 // Link in the function bodies that are defined in the source module into the
1328 // DestModule. This consists basically of copying the function over and
1329 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +00001330 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +00001331
Chris Lattner8166e6e2003-05-13 21:33:43 +00001332 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001333 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1334
Anton Korobeynikov3db91912008-03-05 23:08:47 +00001335 // Resolve all uses of aliases with aliasees
1336 if (ResolveAliases(Dest)) return true;
1337
Reid Spencer57a0efa2004-09-11 04:25:17 +00001338 // If the source library's module id is in the dependent library list of the
1339 // destination library, remove it since that module is now linked in.
1340 sys::Path modId;
Reid Spencerdd04df02005-07-07 23:21:43 +00001341 modId.set(Src->getModuleIdentifier());
Reid Spencer07adb282004-11-05 22:15:36 +00001342 if (!modId.isEmpty())
1343 Dest->removeLibrary(modId.getBasename());
Reid Spencer57a0efa2004-09-11 04:25:17 +00001344
Chris Lattner52f7e902001-10-13 07:03:50 +00001345 return false;
1346}
Vikram S. Adve9466f512001-10-28 21:38:02 +00001347
Reid Spencer567bc2c2004-05-25 08:52:20 +00001348// vim: sw=2