blob: a05ef2b18157ac6abe8f1d2113e4bda5f5166c0b [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"
Bill Wendling7f512482010-10-06 06:16:30 +000022#include "llvm/Instructions.h"
Owen Andersonc9ab7bf2009-07-07 21:07:14 +000023#include "llvm/LLVMContext.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000024#include "llvm/Module.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000025#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000026#include "llvm/ValueSymbolTable.h"
David Greene0fbf0e32010-01-05 01:27:59 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner74382b72009-08-23 22:45:37 +000029#include "llvm/Support/raw_ostream.h"
Reid Spencer57a0efa2004-09-11 04:25:17 +000030#include "llvm/System/Path.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000031#include "llvm/Transforms/Utils/ValueMapper.h"
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...
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +000036static inline bool Error(std::string *E, const Twine &Message) {
37 if (E) *E = Message.str();
Chris Lattner5c377c52001-10-14 23:29:15 +000038 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
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +000080 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
81 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
Chris Lattnerfc196f92008-06-16 23:06:51 +000082public:
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 /// insert - This returns true if the pointer was new to the set, false if it
99 /// was already in the set.
100 bool insert(const Type *Src, const Type *Dst) {
Dan Gohman6b345ee2008-07-07 17:46:23 +0000101 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
Chris Lattner62a81a12008-06-16 21:00:18 +0000102 return false; // Already in map.
103 if (Src->isAbstract())
104 Src->addAbstractTypeUser(this);
105 return true;
106 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000107
Chris Lattner62a81a12008-06-16 21:00:18 +0000108protected:
109 /// refineAbstractType - The callback method invoked when an abstract type is
110 /// resolved to another type. An object must override this method to update
111 /// its internal state to reference NewType instead of OldType.
112 ///
113 virtual void refineAbstractType(const DerivedType *OldTy,
114 const Type *NewTy) {
115 TheMapTy::iterator I = TheMap.find(OldTy);
116 const Type *DstTy = I->second;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000117
Chris Lattner62a81a12008-06-16 21:00:18 +0000118 TheMap.erase(I);
119 if (OldTy->isAbstract())
120 OldTy->removeAbstractTypeUser(this);
121
122 // Don't reinsert into the map if the key is concrete now.
123 if (NewTy->isAbstract())
124 insert(NewTy, DstTy);
125 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000126
Chris Lattner62a81a12008-06-16 21:00:18 +0000127 /// The other case which AbstractTypeUsers must be aware of is when a type
128 /// makes the transition from being abstract (where it has clients on it's
129 /// AbstractTypeUsers list) to concrete (where it does not). This method
130 /// notifies ATU's when this occurs for a type.
131 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
132 TheMap.erase(AbsTy);
133 AbsTy->removeAbstractTypeUser(this);
134 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000135
Chris Lattner62a81a12008-06-16 21:00:18 +0000136 // for debugging...
137 virtual void dump() const {
David Greene0fbf0e32010-01-05 01:27:59 +0000138 dbgs() << "AbstractTypeSet!\n";
Chris Lattner62a81a12008-06-16 21:00:18 +0000139 }
140};
141}
142
143
Chris Lattnere76c57a2003-08-22 06:07:12 +0000144// RecursiveResolveTypes - This is just like ResolveTypes, except that it
145// recurses down into derived types, merging the used types if the parent types
146// are compatible.
Chris Lattnera4477f92008-06-16 21:17:12 +0000147static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner62a81a12008-06-16 21:00:18 +0000148 LinkerTypeMap &Pointers) {
Chris Lattnera4477f92008-06-16 21:17:12 +0000149 if (DstTy == SrcTy) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +0000150
Chris Lattnere76c57a2003-08-22 06:07:12 +0000151 // If we found our opaque type, resolve it now!
Duncan Sands47c51882010-02-16 14:50:09 +0000152 if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy())
Chris Lattnera4477f92008-06-16 21:17:12 +0000153 return ResolveTypes(DstTy, SrcTy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000154
Chris Lattnere76c57a2003-08-22 06:07:12 +0000155 // Two types cannot be resolved together if they are of different primitive
156 // type. For example, we cannot resolve an int to a float.
Chris Lattnera4477f92008-06-16 21:17:12 +0000157 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000158
Chris Lattner56539652008-06-16 20:03:01 +0000159 // If neither type is abstract, then they really are just different types.
Chris Lattnera4477f92008-06-16 21:17:12 +0000160 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattner56539652008-06-16 20:03:01 +0000161 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000162
Chris Lattnere76c57a2003-08-22 06:07:12 +0000163 // Otherwise, resolve the used type used by this derived type...
Chris Lattnera4477f92008-06-16 21:17:12 +0000164 switch (DstTy->getTypeID()) {
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000165 default:
166 return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000167 case Type::FunctionTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000168 const FunctionType *DstFT = cast<FunctionType>(DstTy);
169 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000170 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
171 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000172 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000173
Chris Lattnera4477f92008-06-16 21:17:12 +0000174 // Use TypeHolder's so recursive resolution won't break us.
175 PATypeHolder ST(SrcFT), DT(DstFT);
176 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
177 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
178 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000179 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000180 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000181 return false;
182 }
183 case Type::StructTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000184 const StructType *DstST = cast<StructType>(DstTy);
185 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000186 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000187 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000188
Chris Lattnera4477f92008-06-16 21:17:12 +0000189 PATypeHolder ST(SrcST), DT(DstST);
190 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
191 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
192 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000193 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000194 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000195 return false;
196 }
197 case Type::ArrayTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000198 const ArrayType *DAT = cast<ArrayType>(DstTy);
199 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000200 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000201 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000202 Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000203 }
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000204 case Type::VectorTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000205 const VectorType *DVT = cast<VectorType>(DstTy);
206 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000207 if (DVT->getNumElements() != SVT->getNumElements()) return true;
208 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
209 Pointers);
210 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000211 case Type::PointerTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000212 const PointerType *DstPT = cast<PointerType>(DstTy);
213 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000214
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000215 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
216 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000217
Chris Lattnere3092c92003-08-23 21:25:54 +0000218 // If this is a pointer type, check to see if we have already seen it. If
219 // so, we are in a recursive branch. Cut off the search now. We cannot use
220 // an associative container for this search, because the type pointers (keys
Chris Lattner62a81a12008-06-16 21:00:18 +0000221 // in the container) change whenever types get resolved.
222 if (SrcPT->isAbstract())
223 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
224 return ExistingDestTy != DstPT;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000225
Chris Lattner62a81a12008-06-16 21:00:18 +0000226 if (DstPT->isAbstract())
227 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
228 return ExistingSrcTy != SrcPT;
Chris Lattnere3092c92003-08-23 21:25:54 +0000229 // Otherwise, add the current pointers to the vector to stop recursion on
230 // this pair.
Chris Lattner62a81a12008-06-16 21:00:18 +0000231 if (DstPT->isAbstract())
232 Pointers.insert(DstPT, SrcPT);
233 if (SrcPT->isAbstract())
234 Pointers.insert(SrcPT, DstPT);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000235
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000236 return RecursiveResolveTypesI(DstPT->getElementType(),
237 SrcPT->getElementType(), Pointers);
Chris Lattnere3092c92003-08-23 21:25:54 +0000238 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000239 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000240}
241
Chris Lattnera4477f92008-06-16 21:17:12 +0000242static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner62a81a12008-06-16 21:00:18 +0000243 LinkerTypeMap PointerTypes;
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000244 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Chris Lattnere3092c92003-08-23 21:25:54 +0000245}
246
Chris Lattnere76c57a2003-08-22 06:07:12 +0000247
Chris Lattner2c236f32001-11-03 05:18:24 +0000248// LinkTypes - Go through the symbol table of the Src module and see if any
249// types are named in the src module that are not named in the Dst module.
250// Make sure there are no type name conflicts.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000251static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000252 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
253 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000254
255 // Look for a type plane for Type's...
Reid Spencer78d033e2007-01-06 07:24:44 +0000256 TypeSymbolTable::const_iterator TI = SrcST->begin();
257 TypeSymbolTable::const_iterator TE = SrcST->end();
Reid Spencer567bc2c2004-05-25 08:52:20 +0000258 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000259
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000260 // Some types cannot be resolved immediately because they depend on other
261 // types being resolved to each other first. This contains a list of types we
262 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000263 std::vector<std::string> DelayedTypesToResolve;
264
Reid Spencer567bc2c2004-05-25 08:52:20 +0000265 for ( ; TI != TE; ++TI ) {
266 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000267 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000268
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000269 // Check to see if this type name is already in the dest module.
Reid Spencer78d033e2007-01-06 07:24:44 +0000270 Type *Entry = DestST->lookup(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000271
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000272 // If the name is just in the source module, bring it over to the dest.
273 if (Entry == 0) {
274 if (!Name.empty())
275 DestST->insert(Name, const_cast<Type*>(RHS));
276 } else if (ResolveTypes(Entry, RHS)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000277 // They look different, save the types 'till later to resolve.
278 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000279 }
280 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000281
282 // Iteratively resolve types while we can...
283 while (!DelayedTypesToResolve.empty()) {
284 // Loop over all of the types, attempting to resolve them if possible...
285 unsigned OldSize = DelayedTypesToResolve.size();
286
Chris Lattnere76c57a2003-08-22 06:07:12 +0000287 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000288 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
289 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000290 Type *T1 = SrcST->lookup(Name);
291 Type *T2 = DestST->lookup(Name);
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000292 if (!ResolveTypes(T2, T1)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000293 // We are making progress!
294 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
295 --i;
296 }
297 }
298
299 // Did we not eliminate any types?
300 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000301 // Attempt to resolve subelements of types. This allows us to merge these
302 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000303 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
304 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnera4477f92008-06-16 21:17:12 +0000305 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000306 // We are making progress!
307 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000308
Chris Lattnere76c57a2003-08-22 06:07:12 +0000309 // Go back to the main loop, perhaps we can resolve directly by name
310 // now...
311 break;
312 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000313 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000314
315 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000316 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000317 // Remove the symbol name from the destination.
318 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000319 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000320 }
321 }
322
323
Chris Lattner2c236f32001-11-03 05:18:24 +0000324 return false;
325}
326
Reid Spencer8bef0372007-02-04 04:29:21 +0000327/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
328/// in the symbol table. This is good for all clients except for us. Go
329/// through the trouble to force this back.
Chris Lattnerc0036282004-08-04 07:05:54 +0000330static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
331 assert(GV->getName() != Name && "Can't force rename to self");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000332 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
Chris Lattnerc0036282004-08-04 07:05:54 +0000333
334 // If there is a conflict, rename the conflict.
Chris Lattner33f29492007-02-11 00:39:38 +0000335 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000336 assert(ConflictGV->hasLocalLinkage() &&
Reid Spenceref9b9a72007-02-05 20:47:22 +0000337 "Not conflicting with a static global, should link instead!");
Chris Lattner33f29492007-02-11 00:39:38 +0000338 GV->takeName(ConflictGV);
339 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Reid Spenceref9b9a72007-02-05 20:47:22 +0000340 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000341 } else {
342 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000343 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000344}
Reid Spencer8bef0372007-02-04 04:29:21 +0000345
Reid Spenceref9b9a72007-02-05 20:47:22 +0000346/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000347/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000348static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000349 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
350 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
351 DestGV->copyAttributesFrom(SrcGV);
352 DestGV->setAlignment(Alignment);
Chris Lattnerc0036282004-08-04 07:05:54 +0000353}
354
Chris Lattneraee38ea2004-12-03 22:18:41 +0000355/// GetLinkageResult - This analyzes the two global values and determines what
356/// the result will look like in the destination module. In particular, it
357/// computes the resultant linkage type, computes whether the global in the
358/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000359/// one), and computes whether this linkage is an error or not. It also performs
360/// visibility checks: we cannot link together two symbols with different
361/// visibilities.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000362static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Chris Lattneraee38ea2004-12-03 22:18:41 +0000363 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
364 std::string *Err) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000365 assert((!Dest || !Src->hasLocalLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000366 "If Src has internal linkage, Dest shouldn't be set!");
367 if (!Dest) {
368 // Linking something to nothing.
369 LinkFromSrc = true;
370 LT = Src->getLinkage();
Reid Spencer5cbf9852007-01-30 20:08:39 +0000371 } else if (Src->isDeclaration()) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000372 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000373 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000374 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000375 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000376 if (Dest->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000377 LinkFromSrc = true;
378 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000379 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000380 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000381 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000382 LinkFromSrc = true;
383 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000384 } else {
385 LinkFromSrc = false;
386 LT = Dest->getLinkage();
387 }
Reid Spencer5cbf9852007-01-30 20:08:39 +0000388 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000389 // If Dest is external but Src is not:
390 LinkFromSrc = true;
391 LT = Src->getLinkage();
392 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
393 if (Src->getLinkage() != Dest->getLinkage())
394 return Error(Err, "Linking globals named '" + Src->getName() +
395 "': can only link appending global with another appending global!");
396 LinkFromSrc = true; // Special cased.
397 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000398 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000399 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
400 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000401 if (Dest->hasExternalWeakLinkage() ||
402 Dest->hasAvailableExternallyLinkage() ||
403 (Dest->hasLinkOnceLinkage() &&
404 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000405 LinkFromSrc = true;
406 LT = Src->getLinkage();
407 } else {
408 LinkFromSrc = false;
409 LT = Dest->getLinkage();
410 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000411 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000412 // At this point we know that Src has External* or DLL* linkage.
413 if (Src->hasExternalWeakLinkage()) {
414 LinkFromSrc = false;
415 LT = Dest->getLinkage();
416 } else {
417 LinkFromSrc = true;
418 LT = GlobalValue::ExternalLinkage;
419 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000420 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000421 assert((Dest->hasExternalLinkage() ||
422 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000423 Dest->hasDLLExportLinkage() ||
424 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000425 (Src->hasExternalLinkage() ||
426 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000427 Src->hasDLLExportLinkage() ||
428 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000429 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000430 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000431 "': symbol multiply defined!");
432 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000433
434 // Check visibility
435 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattner97f8b092007-08-19 22:22:54 +0000436 if (!Src->isDeclaration() && !Dest->isDeclaration())
437 return Error(Err, "Linking globals named '" + Src->getName() +
438 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000439 return false;
440}
Chris Lattner5c377c52001-10-14 23:29:15 +0000441
Devang Patelab67e702009-08-11 18:01:24 +0000442// Insert all of the named mdnoes in Src into the Dest module.
Dan Gohmane5835fb2010-08-24 19:31:04 +0000443static void LinkNamedMDNodes(Module *Dest, Module *Src,
444 ValueToValueMapTy &ValueMap) {
Devang Patelab67e702009-08-11 18:01:24 +0000445 for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
446 E = Src->named_metadata_end(); I != E; ++I) {
447 const NamedMDNode *SrcNMD = I;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000448 NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName());
449 // Add Src elements into Dest node.
450 for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
Dan Gohmane5835fb2010-08-24 19:31:04 +0000451 DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i),
Dan Gohman6cb8c232010-08-26 15:41:53 +0000452 ValueMap,
453 true)));
Devang Patelab67e702009-08-11 18:01:24 +0000454 }
455}
456
Bill Wendling7f512482010-10-06 06:16:30 +0000457// RequiresMerge - Return true if the source global variable needs to be merged
458// with the destination global variable. I.e., there shouldn't be a new global
459// variable created in the destination Module, rather the initializers should be
460// merged in an intelligent fashion.
461static bool RequiresMerge(const GlobalVariable *SGV, const GlobalVariable *DGV){
462 const StringRef SrcSec(SGV->getSection());
463 const StringRef DstSec(DGV->getSection());
464
465 // The Objective-C __image_info section should be unique.
466 if (SrcSec == DstSec &&
467 (SrcSec.find("__objc_imageinfo") != StringRef::npos ||
468 SrcSec.find("__image_info") != StringRef::npos))
469 return true;
470
471 return false;
472}
473
Chris Lattner5c377c52001-10-14 23:29:15 +0000474// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000475// them into the dest module.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000476static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000477 ValueToValueMapTy &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000478 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000479 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000480 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000481
Chris Lattner5c377c52001-10-14 23:29:15 +0000482 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner0bb87572008-07-14 05:52:33 +0000483 for (Module::const_global_iterator I = Src->global_begin(),
484 E = Src->global_end(); I != E; ++I) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000485 const GlobalVariable *SGV = I;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000486 GlobalValue *DGV = 0;
487
Bill Wendling7f512482010-10-06 06:16:30 +0000488 GlobalValue *SymTabGV =
489 cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
490
491 // Check to see if the symbol exists in the destination module and needs to
492 // be merged instead of replaced.
493 if (SymTabGV) {
494 const GlobalVariable *GV = dyn_cast<GlobalVariable>(SymTabGV);
495 if (GV && RequiresMerge(SGV, GV)) {
496 // Make sure to remember this mapping.
497 ValueMap[SGV] = SymTabGV;
498 continue;
499 }
500 }
501
502 // Check to see if we may have to link the global with a global, alias, or
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000503 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000504 if (SGV->hasName() && !SGV->hasLocalLinkage())
Bill Wendling7f512482010-10-06 06:16:30 +0000505 DGV = SymTabGV;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000506
Chris Lattnerae1132d2008-07-14 06:52:19 +0000507 // If we found a global with the same name in the dest module, but it has
508 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000509 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000510 DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000511
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000512 // If types don't agree due to opaque types, try to resolve them.
513 if (DGV && DGV->getType() != SGV->getType())
514 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000515
Dan Gohmanc3183292007-10-08 15:13:30 +0000516 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
517 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000518 "Global must either be external or have an initializer!");
519
Chris Lattnerb324bd72006-11-09 05:18:12 +0000520 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
521 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000522 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
523 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000524
Chris Lattner6157e382008-07-14 07:23:24 +0000525 if (DGV == 0) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000526 // No linking to be performed, simply create an identical version of the
527 // symbol over in the dest module... the initializer will be filled in
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000528 // later by LinkGlobalInits.
Chris Lattner2719bac2003-04-21 21:15:04 +0000529 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000530 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Chris Lattner2719bac2003-04-21 21:15:04 +0000531 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000532 SGV->getName(), 0, false,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000533 SGV->getType()->getAddressSpace());
Reid Spencer471feac2007-02-04 04:30:33 +0000534 // Propagate alignment, visibility and section info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000535 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000536
Chris Lattner2719bac2003-04-21 21:15:04 +0000537 // If the LLVM runtime renamed the global, but it is an externally visible
538 // symbol, DGV must be an existing global with internal linkage. Rename
539 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000540 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
Chris Lattnerc0036282004-08-04 07:05:54 +0000541 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000542
Chris Lattner6157e382008-07-14 07:23:24 +0000543 // Make sure to remember this mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000544 ValueMap[SGV] = NewDGV;
545
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000546 // Keep track that this is an appending variable.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000547 if (SGV->hasAppendingLinkage())
Chris Lattner8166e6e2003-05-13 21:33:43 +0000548 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000549 continue;
550 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000551
Chris Lattner6157e382008-07-14 07:23:24 +0000552 // If the visibilities of the symbols disagree and the destination is a
553 // prototype, take the visibility of its input.
554 if (DGV->isDeclaration())
555 DGV->setVisibility(SGV->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000556
Chris Lattner6157e382008-07-14 07:23:24 +0000557 if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000558 // No linking is performed yet. Just insert a new copy of the global, and
559 // keep track of the fact that it is an appending variable in the
560 // AppendingVars map. The name is cleared out so that no linkage is
561 // performed.
562 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000563 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Chris Lattner8166e6e2003-05-13 21:33:43 +0000564 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000565 "", 0, false,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000566 SGV->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +0000567
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000568 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000569 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000570 // Propagate alignment, section and visibility info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000571 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000572
Chris Lattner8166e6e2003-05-13 21:33:43 +0000573 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000574 ValueMap[SGV] = NewDGV;
Chris Lattner8166e6e2003-05-13 21:33:43 +0000575
576 // Keep track that this is an appending variable...
577 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000578 continue;
579 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000580
Chris Lattner6157e382008-07-14 07:23:24 +0000581 if (LinkFromSrc) {
582 if (isa<GlobalAlias>(DGV))
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000583 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
584 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000585
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000586 // If the types don't match, and if we are to link from the source, nuke
587 // DGV and create a new one of the appropriate type. Note that the thing
588 // we are replacing may be a function (if a prototype, weak, etc) or a
589 // global variable.
590 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000591 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000592 SGV->isConstant(), NewLinkage, /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000593 DGV->getName(), 0, false,
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000594 SGV->getType()->getAddressSpace());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000595
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000596 // Propagate alignment, section, and visibility info.
597 CopyGVAttributes(NewDGV, SGV);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000598 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000599 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000600
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000601 // DGV will conflict with NewDGV because they both had the same
602 // name. We must erase this now so ForceRenaming doesn't assert
603 // because DGV might not have internal linkage.
604 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
605 Var->eraseFromParent();
606 else
607 cast<Function>(DGV)->eraseFromParent();
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000608
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000609 // If the symbol table renamed the global, but it is an externally visible
610 // symbol, DGV must be an existing global with internal linkage. Rename.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000611 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000612 ForceRenaming(NewDGV, SGV->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000613
Chris Lattner6157e382008-07-14 07:23:24 +0000614 // Inherit const as appropriate.
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000615 NewDGV->setConstant(SGV->isConstant());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000616
Chris Lattner6157e382008-07-14 07:23:24 +0000617 // Make sure to remember this mapping.
618 ValueMap[SGV] = NewDGV;
619 continue;
Chris Lattner5c377c52001-10-14 23:29:15 +0000620 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000621
Chris Lattner6157e382008-07-14 07:23:24 +0000622 // Not "link from source", keep the one in the DestModule and remap the
623 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000624
Chris Lattner6157e382008-07-14 07:23:24 +0000625 // Special case for const propagation.
626 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
627 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
628 DGVar->setConstant(true);
629
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000630 // SGV is global, but DGV is alias.
631 if (isa<GlobalAlias>(DGV)) {
632 // The only valid mappings are:
633 // - SGV is external declaration, which is effectively a no-op.
634 // - SGV is weak, when we just need to throw SGV out.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000635 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000636 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
637 "': symbol multiple defined");
638 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000639
Chris Lattner6157e382008-07-14 07:23:24 +0000640 // Set calculated linkage
641 DGV->setLinkage(NewLinkage);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000642
Chris Lattner6157e382008-07-14 07:23:24 +0000643 // Make sure to remember this mapping...
Owen Andersonbaf3c402009-07-29 18:55:55 +0000644 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000645 }
646 return false;
647}
648
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000649static GlobalValue::LinkageTypes
650CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000651 GlobalValue::LinkageTypes SL = SGV->getLinkage();
652 GlobalValue::LinkageTypes DL = DGV->getLinkage();
653 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000654 return GlobalValue::ExternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +0000655 else if (SL == GlobalValue::WeakAnyLinkage ||
656 DL == GlobalValue::WeakAnyLinkage)
657 return GlobalValue::WeakAnyLinkage;
658 else if (SL == GlobalValue::WeakODRLinkage ||
659 DL == GlobalValue::WeakODRLinkage)
660 return GlobalValue::WeakODRLinkage;
661 else if (SL == GlobalValue::InternalLinkage &&
662 DL == GlobalValue::InternalLinkage)
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000663 return GlobalValue::InternalLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000664 else if (SL == GlobalValue::LinkerPrivateLinkage &&
665 DL == GlobalValue::LinkerPrivateLinkage)
666 return GlobalValue::LinkerPrivateLinkage;
Bill Wendling4e34d502010-08-24 20:00:52 +0000667 else if (SL == GlobalValue::LinkerPrivateWeakLinkage &&
668 DL == GlobalValue::LinkerPrivateWeakLinkage)
669 return GlobalValue::LinkerPrivateWeakLinkage;
670 else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage &&
671 DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage)
672 return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000673 else {
Duncan Sands667d4b82009-03-07 15:45:40 +0000674 assert (SL == GlobalValue::PrivateLinkage &&
675 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
Rafael Espindolabb46f522009-01-15 20:18:42 +0000676 return GlobalValue::PrivateLinkage;
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000677 }
678}
679
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000680// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000681// dest module. We're assuming, that all functions/global variables were already
682// linked in.
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000683static bool LinkAlias(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000684 ValueToValueMapTy &ValueMap,
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000685 std::string *Err) {
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000686 // Loop over all alias in the src module
687 for (Module::const_alias_iterator I = Src->alias_begin(),
688 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000689 const GlobalAlias *SGA = I;
690 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
691 GlobalAlias *NewGA = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000692
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000693 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000694 // of SAliasee in Dest.
Dan Gohman05ea54e2010-08-24 18:50:07 +0000695 ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee);
Ted Kremenek58d5e052008-03-09 18:32:50 +0000696 assert(VMI != ValueMap.end() && "Aliasee not linked");
697 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000698 GlobalValue* DGV = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000699
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000700 // Try to find something 'similar' to SGA in destination module.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000701 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000702 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000703
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000704 // If types don't agree due to opaque types, try to resolve them.
705 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000706 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000707 }
708
Rafael Espindolabb46f522009-01-15 20:18:42 +0000709 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000710 DGV = Dest->getGlobalVariable(SGA->getName());
711
712 // If types don't agree due to opaque types, try to resolve them.
713 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000714 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000715 }
716
Rafael Espindolabb46f522009-01-15 20:18:42 +0000717 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000718 DGV = Dest->getFunction(SGA->getName());
719
720 // If types don't agree due to opaque types, try to resolve them.
721 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000722 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000723 }
724
725 // No linking to be performed on internal stuff.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000726 if (DGV && DGV->hasLocalLinkage())
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000727 DGV = NULL;
728
729 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
730 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000731 // globals are already linked we just need query ValueMap to find the
732 // mapping.
733 if (DAliasee == DGA->getAliasedGlobal()) {
734 // This is just two copies of the same alias. Propagate linkage, if
735 // necessary.
736 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
737
738 NewGA = DGA;
739 // Proceed to 'common' steps
740 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000741 return Error(Err, "Alias Collision on '" + SGA->getName()+
742 "': aliases have different aliasees");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000743 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000744 // The only allowed way is to link alias with external declaration or weak
745 // symbol..
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000746 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000747 // But only if aliasee is global too...
748 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000749 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
750 "': aliasee is not global variable");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000751
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000752 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
753 SGA->getName(), DAliasee, Dest);
754 CopyGVAttributes(NewGA, SGA);
755
756 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000757 if (SGA->getType() != DGVar->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000758 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000759 DGVar->getType()));
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000760 else
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000761 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000762
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000763 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000764 // name. We must erase this now so ForceRenaming doesn't assert
765 // because DGV might not have internal linkage.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000766 DGVar->eraseFromParent();
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000767
768 // Proceed to 'common' steps
769 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000770 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
771 "': symbol multiple defined");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000772 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000773 // The only allowed way is to link alias with external declaration or weak
774 // symbol...
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000775 if (DF->isDeclaration() || DF->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000776 // But only if aliasee is function too...
777 if (!isa<Function>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000778 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
779 "': aliasee is not function");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000780
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000781 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
782 SGA->getName(), DAliasee, Dest);
783 CopyGVAttributes(NewGA, SGA);
784
785 // Any uses of DF need to change to NewGA, with cast, if needed.
786 if (SGA->getType() != DF->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000787 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000788 DF->getType()));
789 else
790 DF->replaceAllUsesWith(NewGA);
791
792 // DF will conflict with NewGA because they both had the same
793 // name. We must erase this now so ForceRenaming doesn't assert
794 // because DF might not have internal linkage.
795 DF->eraseFromParent();
796
797 // Proceed to 'common' steps
798 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000799 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
800 "': symbol multiple defined");
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000801 } else {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000802 // No linking to be performed, simply create an identical version of the
803 // alias over in the dest module...
David Chisnall34722462010-01-09 16:27:31 +0000804 Constant *Aliasee = DAliasee;
805 // Fixup aliases to bitcasts. Note that aliases to GEPs are still broken
806 // by this, but aliases to GEPs are broken to a lot of other things, so
807 // it's less important.
808 if (SGA->getType() != DAliasee->getType())
809 Aliasee = ConstantExpr::getBitCast(DAliasee, SGA->getType());
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000810 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
David Chisnall34722462010-01-09 16:27:31 +0000811 SGA->getName(), Aliasee, Dest);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000812 CopyGVAttributes(NewGA, SGA);
813
814 // Proceed to 'common' steps
815 }
816
817 assert(NewGA && "No alias was created in destination module!");
818
Anton Korobeynikovb8cdaf72008-03-10 22:36:35 +0000819 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000820 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000821 if (NewGA->getName() != SGA->getName() &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000822 !NewGA->hasLocalLinkage())
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000823 ForceRenaming(NewGA, SGA->getName());
824
825 // Remember this mapping so uses in the source module get remapped
Dan Gohman05ea54e2010-08-24 18:50:07 +0000826 // later by MapValue.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000827 ValueMap[SGA] = NewGA;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000828 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000829
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000830 return false;
831}
832
Chris Lattner5c377c52001-10-14 23:29:15 +0000833
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000834// LinkGlobalInits - Update the initializers in the Dest module now that all
835// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000836static bool LinkGlobalInits(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000837 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000838 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000839 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000840 for (Module::const_global_iterator I = Src->global_begin(),
841 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000842 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000843
844 if (SGV->hasInitializer()) { // Only process initialized GV's
845 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000846 Constant *SInit =
Dan Gohman6cb8c232010-08-26 15:41:53 +0000847 cast<Constant>(MapValue(SGV->getInitializer(), ValueMap, true));
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000848 // Grab destination global variable or alias.
849 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000850
Bill Wendling7f512482010-10-06 06:16:30 +0000851 // If dest is a global variable, check that initializers match.
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000852 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
853 if (DGVar->hasInitializer()) {
Bill Wendling7f512482010-10-06 06:16:30 +0000854 if (SGV->hasExternalLinkage() || RequiresMerge(SGV, DGVar)) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000855 if (DGVar->getInitializer() != SInit)
856 return Error(Err, "Global Variable Collision on '" +
857 SGV->getName() +
858 "': global variables have different initializers");
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000859 } else if (DGVar->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000860 // Nothing is required, mapped values will take the new global
861 // automatically.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000862 } else if (SGV->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000863 // Nothing is required, mapped values will take the new global
864 // automatically.
865 } else if (DGVar->hasAppendingLinkage()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000866 llvm_unreachable("Appending linkage unimplemented!");
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000867 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000868 llvm_unreachable("Unknown linkage!");
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000869 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000870 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000871 // Copy the initializer over now...
872 DGVar->setInitializer(SInit);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000873 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000874 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000875 // Destination is alias, the only valid situation is when source is
876 // weak. Also, note, that we already checked linkage in LinkGlobals(),
877 // thus we assert here.
878 // FIXME: Should we weaken this assumption, 'dereference' alias and
879 // check for initializer of aliasee?
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000880 assert(SGV->isWeakForLinker());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000881 }
882 }
883 }
884 return false;
885}
Chris Lattner5c377c52001-10-14 23:29:15 +0000886
Chris Lattner79df7c02002-03-26 18:01:55 +0000887// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000888// without doing function bodies... this just adds external function prototypes
889// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000890//
Chris Lattner79df7c02002-03-26 18:01:55 +0000891static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000892 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000893 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000894 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000895
Reid Spencer619f0242007-02-04 04:43:17 +0000896 // Loop over all of the functions in the src module, mapping them over
Chris Lattner5c377c52001-10-14 23:29:15 +0000897 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000898 const Function *SF = I; // SrcFunction
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000899 GlobalValue *DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000900
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000901 // Check to see if may have to link the function with the global, alias or
902 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000903 if (SF->hasName() && !SF->hasLocalLinkage())
Daniel Dunbar03d76512009-07-25 23:55:21 +0000904 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000905
Chris Lattnerae1132d2008-07-14 06:52:19 +0000906 // If we found a global with the same name in the dest module, but it has
907 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000908 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000909 DGV = 0;
910
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000911 // If types don't agree due to opaque types, try to resolve them.
912 if (DGV && DGV->getType() != SF->getType())
913 RecursiveResolveTypes(SF->getType(), DGV->getType());
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000914
Chris Lattner6157e382008-07-14 07:23:24 +0000915 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
916 bool LinkFromSrc = false;
917 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
918 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000919
Chris Lattner82468492008-06-09 07:36:11 +0000920 // If there is no linkage to be performed, just bring over SF without
921 // modifying it.
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000922 if (DGV == 0) {
Chris Lattner82468492008-06-09 07:36:11 +0000923 // Function does not already exist, simply insert an function signature
924 // identical to SF into the dest module.
925 Function *NewDF = Function::Create(SF->getFunctionType(),
926 SF->getLinkage(),
927 SF->getName(), Dest);
928 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000929
Chris Lattner82468492008-06-09 07:36:11 +0000930 // If the LLVM runtime renamed the function, but it is an externally
931 // visible symbol, DF must be an existing function with internal linkage.
932 // Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000933 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
Chris Lattner82468492008-06-09 07:36:11 +0000934 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000935
Chris Lattner82468492008-06-09 07:36:11 +0000936 // ... and remember this mapping...
937 ValueMap[SF] = NewDF;
938 continue;
Chris Lattner6157e382008-07-14 07:23:24 +0000939 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000940
Chris Lattner6157e382008-07-14 07:23:24 +0000941 // If the visibilities of the symbols disagree and the destination is a
942 // prototype, take the visibility of its input.
943 if (DGV->isDeclaration())
944 DGV->setVisibility(SF->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000945
Chris Lattner6157e382008-07-14 07:23:24 +0000946 if (LinkFromSrc) {
947 if (isa<GlobalAlias>(DGV))
948 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
949 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000950
Chris Lattner6157e382008-07-14 07:23:24 +0000951 // We have a definition of the same name but different type in the
952 // source module. Copy the prototype to the destination and replace
953 // uses of the destination's prototype with the new prototype.
954 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
955 SF->getName(), Dest);
956 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000957
Chris Lattner6157e382008-07-14 07:23:24 +0000958 // Any uses of DF need to change to NewDF, with cast
Owen Andersonbaf3c402009-07-29 18:55:55 +0000959 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000960 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000961
Chris Lattner6157e382008-07-14 07:23:24 +0000962 // DF will conflict with NewDF because they both had the same. We must
963 // erase this now so ForceRenaming doesn't assert because DF might
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000964 // not have internal linkage.
Chris Lattner6157e382008-07-14 07:23:24 +0000965 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
966 Var->eraseFromParent();
967 else
968 cast<Function>(DGV)->eraseFromParent();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000969
Chris Lattner6157e382008-07-14 07:23:24 +0000970 // If the symbol table renamed the function, but it is an externally
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000971 // visible symbol, DF must be an existing function with internal
Chris Lattner6157e382008-07-14 07:23:24 +0000972 // linkage. Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000973 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
Chris Lattner6157e382008-07-14 07:23:24 +0000974 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000975
Chris Lattner6157e382008-07-14 07:23:24 +0000976 // Remember this mapping so uses in the source module get remapped
Dan Gohman05ea54e2010-08-24 18:50:07 +0000977 // later by MapValue.
Chris Lattner6157e382008-07-14 07:23:24 +0000978 ValueMap[SF] = NewDF;
979 continue;
980 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000981
Chris Lattner6157e382008-07-14 07:23:24 +0000982 // Not "link from source", keep the one in the DestModule and remap the
983 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000984
Chris Lattner6157e382008-07-14 07:23:24 +0000985 if (isa<GlobalAlias>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000986 // The only valid mappings are:
987 // - SF is external declaration, which is effectively a no-op.
988 // - SF is weak, when we just need to throw SF out.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000989 if (!SF->isDeclaration() && !SF->isWeakForLinker())
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000990 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
991 "': symbol multiple defined");
Chris Lattner82468492008-06-09 07:36:11 +0000992 }
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000993
Chris Lattner6157e382008-07-14 07:23:24 +0000994 // Set calculated linkage
995 DGV->setLinkage(NewLinkage);
Chris Lattner5c377c52001-10-14 23:29:15 +0000996
Chris Lattner6157e382008-07-14 07:23:24 +0000997 // Make sure to remember this mapping.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000998 ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000999 }
1000 return false;
1001}
1002
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001003// LinkFunctionBody - Copy the source function over into the dest function and
1004// fix up references to values. At this point we know that Dest is an external
1005// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001006static bool LinkFunctionBody(Function *Dest, Function *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +00001007 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001008 std::string *Err) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001009 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +00001010
Chris Lattner0033baf2004-11-16 17:12:38 +00001011 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +00001012 Function::arg_iterator DI = Dest->arg_begin();
1013 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +00001014 I != E; ++I, ++DI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +00001015 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +00001016
1017 // Add a mapping to our local map
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +00001018 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +00001019 }
1020
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001021 // Splice the body of the source function into the dest function.
1022 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +00001023
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001024 // At this point, all of the instructions and values of the function are now
1025 // copied over. The only problem is that they are still referencing values in
1026 // the Source function as operands. Loop through all of the operands of the
1027 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +00001028 //
Dan Gohman6cb8c232010-08-26 15:41:53 +00001029 // This is the same as RemapInstruction, except that it avoids remapping
1030 // instruction and basic block operands.
1031 //
Chris Lattner18961502002-06-25 16:12:52 +00001032 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
Dan Gohman6cb8c232010-08-26 15:41:53 +00001033 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1034 // Remap operands.
Chris Lattner18961502002-06-25 16:12:52 +00001035 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +00001036 OI != OE; ++OI)
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001037 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Dan Gohman6cb8c232010-08-26 15:41:53 +00001038 *OI = MapValue(*OI, ValueMap, true);
1039
1040 // Remap attached metadata.
1041 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1042 I->getAllMetadata(MDs);
1043 for (SmallVectorImpl<std::pair<unsigned, MDNode *> >::iterator
1044 MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI) {
1045 Value *Old = MI->second;
1046 if (!isa<Instruction>(Old) && !isa<BasicBlock>(Old)) {
1047 Value *New = MapValue(Old, ValueMap, true);
1048 if (New != Old)
1049 I->setMetadata(MI->first, cast<MDNode>(New));
1050 }
1051 }
1052 }
Chris Lattner0033baf2004-11-16 17:12:38 +00001053
1054 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +00001055 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1056 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +00001057 ValueMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +00001058
1059 return false;
1060}
1061
1062
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001063// LinkFunctionBodies - Link in the function bodies that are defined in the
1064// source module into the DestModule. This consists basically of copying the
1065// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001066static bool LinkFunctionBodies(Module *Dest, Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +00001067 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001068 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +00001069
Reid Spencer8bef0372007-02-04 04:29:21 +00001070 // Loop over all of the functions in the src module, mapping them over as we
1071 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001072 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer619f0242007-02-04 04:43:17 +00001073 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001074 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +00001075
Chris Lattner18961502002-06-25 16:12:52 +00001076 // DF not external SF external?
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001077 if (DF && DF->isDeclaration())
Chris Lattner35956552003-10-27 16:39:39 +00001078 // Only provide the function body if there isn't one already.
1079 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1080 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +00001081 }
Chris Lattner5c377c52001-10-14 23:29:15 +00001082 }
1083 return false;
1084}
1085
Chris Lattner8166e6e2003-05-13 21:33:43 +00001086// LinkAppendingVars - If there were any appending global variables, link them
1087// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001088static bool LinkAppendingVars(Module *M,
1089 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1090 std::string *ErrorMsg) {
1091 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +00001092
Chris Lattner8166e6e2003-05-13 21:33:43 +00001093 // Loop over the multimap of appending vars, processing any variables with the
1094 // same name, forming a new appending global variable with both of the
1095 // initializers merged together, then rewrite references to the old variables
1096 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001097 std::vector<Constant*> Inits;
1098 while (AppendingVars.size() > 1) {
1099 // Get the first two elements in the map...
1100 std::multimap<std::string,
1101 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1102
1103 // If the first two elements are for different names, there is no pair...
1104 // Otherwise there is a pair, so link them together...
1105 if (First->first == Second->first) {
1106 GlobalVariable *G1 = First->second, *G2 = Second->second;
1107 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1108 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +00001109
Chris Lattner8166e6e2003-05-13 21:33:43 +00001110 // Check to see that they two arrays agree on type...
1111 if (T1->getElementType() != T2->getElementType())
1112 return Error(ErrorMsg,
1113 "Appending variables with different element types need to be linked!");
1114 if (G1->isConstant() != G2->isConstant())
1115 return Error(ErrorMsg,
1116 "Appending variables linked with different const'ness!");
1117
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001118 if (G1->getAlignment() != G2->getAlignment())
1119 return Error(ErrorMsg,
1120 "Appending variables with different alignment need to be linked!");
1121
1122 if (G1->getVisibility() != G2->getVisibility())
1123 return Error(ErrorMsg,
1124 "Appending variables with different visibility need to be linked!");
1125
1126 if (G1->getSection() != G2->getSection())
1127 return Error(ErrorMsg,
1128 "Appending variables with different section name need to be linked!");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001129
Chris Lattner8166e6e2003-05-13 21:33:43 +00001130 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
Owen Andersondebcb012009-07-29 22:17:13 +00001131 ArrayType *NewType = ArrayType::get(T1->getElementType(),
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001132 NewSize);
Chris Lattner8166e6e2003-05-13 21:33:43 +00001133
Chris Lattnered74a4e2005-12-06 17:30:58 +00001134 G1->setName(""); // Clear G1's name in case of a conflict!
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001135
Chris Lattner8166e6e2003-05-13 21:33:43 +00001136 // Create the new global variable...
1137 GlobalVariable *NG =
Owen Andersone9b11b42009-07-08 19:03:57 +00001138 new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1139 /*init*/0, First->first, 0, G1->isThreadLocal(),
Chris Lattnera534b0f2008-06-27 03:10:24 +00001140 G1->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +00001141
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001142 // Propagate alignment, visibility and section info.
1143 CopyGVAttributes(NG, G1);
1144
Chris Lattner8166e6e2003-05-13 21:33:43 +00001145 // Merge the initializer...
1146 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +00001147 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1148 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001149 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001150 } else {
1151 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
Owen Andersona7235ea2009-07-31 20:28:14 +00001152 Constant *CV = Constant::getNullValue(T1->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001153 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1154 Inits.push_back(CV);
1155 }
1156 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1157 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001158 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001159 } else {
1160 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
Owen Andersona7235ea2009-07-31 20:28:14 +00001161 Constant *CV = Constant::getNullValue(T2->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001162 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1163 Inits.push_back(CV);
1164 }
Owen Anderson1fd70962009-07-28 18:32:17 +00001165 NG->setInitializer(ConstantArray::get(NewType, Inits));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001166 Inits.clear();
1167
1168 // Replace any uses of the two global variables with uses of the new
1169 // global...
1170
1171 // FIXME: This should rewrite simple/straight-forward uses such as
1172 // getelementptr instructions to not use the Cast!
Owen Andersonbaf3c402009-07-29 18:55:55 +00001173 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001174 G1->getType()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001175 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001176 G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001177
1178 // Remove the two globals from the module now...
1179 M->getGlobalList().erase(G1);
1180 M->getGlobalList().erase(G2);
1181
1182 // Put the new global into the AppendingVars map so that we can handle
1183 // linking of more than two vars...
1184 Second->second = NG;
1185 }
1186 AppendingVars.erase(First);
1187 }
1188
1189 return false;
1190}
Chris Lattner52f7e902001-10-13 07:03:50 +00001191
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001192static bool ResolveAliases(Module *Dest) {
1193 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov52419572008-03-11 22:51:09 +00001194 I != E; ++I)
David Chisnall34722462010-01-09 16:27:31 +00001195 // We can't sue resolveGlobalAlias here because we need to preserve
1196 // bitcasts and GEPs.
1197 if (const Constant *C = I->getAliasee()) {
1198 while (dyn_cast<GlobalAlias>(C))
1199 C = cast<GlobalAlias>(C)->getAliasee();
1200 const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1201 if (C != I && !(GV && GV->isDeclaration()))
1202 I->replaceAllUsesWith(const_cast<Constant*>(C));
1203 }
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001204
1205 return false;
1206}
Chris Lattner52f7e902001-10-13 07:03:50 +00001207
1208// LinkModules - This function links two modules together, with the resulting
1209// left module modified to be the composite of the two input modules. If an
1210// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001211// the problem. Upon failure, the Dest module could be in a modified state, and
1212// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +00001213bool
Reid Spencer0ba9e212004-12-13 03:00:16 +00001214Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +00001215 assert(Dest != 0 && "Invalid Destination module");
1216 assert(Src != 0 && "Invalid Source Module");
1217
Chris Lattnerc36357c2007-01-29 00:21:34 +00001218 if (Dest->getDataLayout().empty()) {
1219 if (!Src->getDataLayout().empty()) {
Chris Lattnerec9bfdc2007-01-29 02:18:13 +00001220 Dest->setDataLayout(Src->getDataLayout());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001221 } else {
1222 std::string DataLayout;
Reid Spencer26f23852007-01-26 08:11:39 +00001223
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001224 if (Dest->getEndianness() == Module::AnyEndianness) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001225 if (Src->getEndianness() == Module::BigEndian)
1226 DataLayout.append("E");
1227 else if (Src->getEndianness() == Module::LittleEndian)
1228 DataLayout.append("e");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001229 }
1230
1231 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001232 if (Src->getPointerSize() == Module::Pointer64)
1233 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1234 else if (Src->getPointerSize() == Module::Pointer32)
1235 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001236 }
Chris Lattnerc36357c2007-01-29 00:21:34 +00001237 Dest->setDataLayout(DataLayout);
1238 }
1239 }
1240
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001241 // Copy the target triple from the source to dest if the dest's is empty.
Chris Lattnerc36357c2007-01-29 00:21:34 +00001242 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
Chris Lattner152f19a2004-12-10 20:26:15 +00001243 Dest->setTargetTriple(Src->getTargetTriple());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001244
Chris Lattnerc36357c2007-01-29 00:21:34 +00001245 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1246 Src->getDataLayout() != Dest->getDataLayout())
Chris Lattnerbdff5482009-08-23 04:37:46 +00001247 errs() << "WARNING: Linking two modules of different data layouts!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +00001248 if (!Src->getTargetTriple().empty() &&
1249 Dest->getTargetTriple() != Src->getTargetTriple())
Chris Lattnerbdff5482009-08-23 04:37:46 +00001250 errs() << "WARNING: Linking two modules of different target triples!\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001251
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001252 // Append the module inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001253 if (!Src->getModuleInlineAsm().empty()) {
1254 if (Dest->getModuleInlineAsm().empty())
1255 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001256 else
Chris Lattner66316012006-01-24 04:14:29 +00001257 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1258 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001259 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001260
Reid Spencer719012d2004-11-25 09:29:44 +00001261 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +00001262 // from the source module. There's no opportunity for duplicates here as the
1263 // Module ensures that duplicate insertions are discarded.
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001264 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001265 SI != SE; ++SI)
Reid Spencer57a0efa2004-09-11 04:25:17 +00001266 Dest->addLibrary(*SI);
Reid Spencer57a0efa2004-09-11 04:25:17 +00001267
Chris Lattner2c236f32001-11-03 05:18:24 +00001268 // LinkTypes - Go through the symbol table of the Src module and see if any
1269 // types are named in the src module that are not named in the Dst module.
1270 // Make sure there are no type name conflicts.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001271 if (LinkTypes(Dest, Src, ErrorMsg))
Reid Spencer619f0242007-02-04 04:43:17 +00001272 return true;
Chris Lattner2c236f32001-11-03 05:18:24 +00001273
Chris Lattner5c377c52001-10-14 23:29:15 +00001274 // ValueMap - Mapping of values from what they used to be in Src, to what they
Dan Gohman05ea54e2010-08-24 18:50:07 +00001275 // are now in Dest. ValueToValueMapTy is a ValueMap, which involves some
1276 // overhead due to the use of Value handles which the Linker doesn't actually
1277 // need, but this allows us to reuse the ValueMapper code.
1278 ValueToValueMapTy ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +00001279
Chris Lattner8166e6e2003-05-13 21:33:43 +00001280 // AppendingVars - Keep track of global variables in the destination module
1281 // with appending linkage. After the module is linked together, they are
1282 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001283 std::multimap<std::string, GlobalVariable *> AppendingVars;
Chris Lattner11273152006-06-16 01:24:04 +00001284 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1285 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +00001286 // Add all of the appending globals already in the Dest module to
1287 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +00001288 if (I->hasAppendingLinkage())
1289 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner5a837de2004-08-04 07:44:58 +00001290 }
1291
Chris Lattner8166e6e2003-05-13 21:33:43 +00001292 // Insert all of the globals in src into the Dest module... without linking
1293 // initializers (which could refer to functions not yet mapped over).
Reid Spenceref9b9a72007-02-05 20:47:22 +00001294 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001295 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001296
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001297 // Link the functions together between the two modules, without doing function
1298 // bodies... this just adds external function prototypes to the Dest
1299 // function... We do this so that when we begin processing function bodies,
1300 // all of the global values that may be referenced are available in our
1301 // ValueMap.
Reid Spenceref9b9a72007-02-05 20:47:22 +00001302 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001303 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001304
Anton Korobeynikov4fb28732008-03-05 15:27:21 +00001305 // If there were any alias, link them now. We really need to do this now,
1306 // because all of the aliases that may be referenced need to be available in
1307 // ValueMap
1308 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1309
Chris Lattner6cdf1972002-07-18 00:13:08 +00001310 // Update the initializers in the Dest module now that all globals that may
1311 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +00001312 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1313
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001314 // Link in the function bodies that are defined in the source module into the
1315 // DestModule. This consists basically of copying the function over and
1316 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +00001317 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +00001318
Chris Lattner8166e6e2003-05-13 21:33:43 +00001319 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001320 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1321
Anton Korobeynikov3db91912008-03-05 23:08:47 +00001322 // Resolve all uses of aliases with aliasees
1323 if (ResolveAliases(Dest)) return true;
1324
Dan Gohmane422d1b2010-08-24 19:37:11 +00001325 // Remap all of the named mdnoes in Src into the Dest module. We do this
1326 // after linking GlobalValues so that MDNodes that reference GlobalValues
1327 // are properly remapped.
1328 LinkNamedMDNodes(Dest, Src, ValueMap);
1329
Reid Spencer57a0efa2004-09-11 04:25:17 +00001330 // If the source library's module id is in the dependent library list of the
1331 // destination library, remove it since that module is now linked in.
1332 sys::Path modId;
Reid Spencerdd04df02005-07-07 23:21:43 +00001333 modId.set(Src->getModuleIdentifier());
Reid Spencer07adb282004-11-05 22:15:36 +00001334 if (!modId.isEmpty())
1335 Dest->removeLibrary(modId.getBasename());
Reid Spencer57a0efa2004-09-11 04:25:17 +00001336
Chris Lattner52f7e902001-10-13 07:03:50 +00001337 return false;
1338}
Vikram S. Adve9466f512001-10-28 21:38:02 +00001339
Reid Spencer567bc2c2004-05-25 08:52:20 +00001340// vim: sw=2