blob: 4b4c72bf278ae9b121877d8f28ab75ad59c6bba5 [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"
Bill Wendling933f9bd2010-10-06 20:18:44 +000026#include "llvm/Instructions.h"
27#include "llvm/Assembly/Writer.h"
David Greene0fbf0e32010-01-05 01:27:59 +000028#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner74382b72009-08-23 22:45:37 +000030#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000031#include "llvm/Support/Path.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000032#include "llvm/Transforms/Utils/ValueMapper.h"
Bill Wendling933f9bd2010-10-06 20:18:44 +000033#include "llvm/ADT/DenseMap.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chris Lattner5c377c52001-10-14 23:29:15 +000036// Error - Simple wrapper function to conditionally assign to E and return true.
37// This just makes error return conditions a little bit simpler...
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +000038static inline bool Error(std::string *E, const Twine &Message) {
39 if (E) *E = Message.str();
Chris Lattner5c377c52001-10-14 23:29:15 +000040 return true;
41}
42
John Criswell700867b2003-11-04 15:22:26 +000043// Function: ResolveTypes()
44//
45// Description:
46// Attempt to link the two specified types together.
47//
48// Inputs:
49// DestTy - The type to which we wish to resolve.
50// SrcTy - The original type which we want to resolve.
John Criswell700867b2003-11-04 15:22:26 +000051//
52// Outputs:
53// DestST - The symbol table in which the new type should be placed.
54//
55// Return value:
56// true - There is an error and the types cannot yet be linked.
57// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000058//
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000059static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000060 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000061 assert(DestTy && SrcTy && "Can't handle null types");
Chris Lattnere76c57a2003-08-22 06:07:12 +000062
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000063 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
64 // Type _is_ in module, just opaque...
65 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
66 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
67 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
68 } else {
69 return true; // Cannot link types... not-equal and neither is opaque.
Chris Lattner4c00e532003-05-15 16:30:55 +000070 }
71 return false;
72}
73
Chris Lattner62a81a12008-06-16 21:00:18 +000074/// LinkerTypeMap - This implements a map of types that is stable
75/// even if types are resolved/refined to other types. This is not a general
76/// purpose map, it is specific to the linker's use.
77namespace {
78class LinkerTypeMap : public AbstractTypeUser {
79 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
80 TheMapTy TheMap;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000081
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +000082 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
83 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
Chris Lattnerfc196f92008-06-16 23:06:51 +000084public:
85 LinkerTypeMap() {}
86 ~LinkerTypeMap() {
Chris Lattner62a81a12008-06-16 21:00:18 +000087 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
88 E = TheMap.end(); I != E; ++I)
89 I->first->removeAbstractTypeUser(this);
90 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000091
Chris Lattner62a81a12008-06-16 21:00:18 +000092 /// lookup - Return the value for the specified type or null if it doesn't
93 /// exist.
94 const Type *lookup(const Type *Ty) const {
95 TheMapTy::const_iterator I = TheMap.find(Ty);
96 if (I != TheMap.end()) return I->second;
97 return 0;
98 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000099
Chris Lattner62a81a12008-06-16 21:00:18 +0000100 /// insert - This returns true if the pointer was new to the set, false if it
101 /// was already in the set.
102 bool insert(const Type *Src, const Type *Dst) {
Dan Gohman6b345ee2008-07-07 17:46:23 +0000103 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
Chris Lattner62a81a12008-06-16 21:00:18 +0000104 return false; // Already in map.
105 if (Src->isAbstract())
106 Src->addAbstractTypeUser(this);
107 return true;
108 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000109
Chris Lattner62a81a12008-06-16 21:00:18 +0000110protected:
111 /// refineAbstractType - The callback method invoked when an abstract type is
112 /// resolved to another type. An object must override this method to update
113 /// its internal state to reference NewType instead of OldType.
114 ///
115 virtual void refineAbstractType(const DerivedType *OldTy,
116 const Type *NewTy) {
117 TheMapTy::iterator I = TheMap.find(OldTy);
118 const Type *DstTy = I->second;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000119
Chris Lattner62a81a12008-06-16 21:00:18 +0000120 TheMap.erase(I);
121 if (OldTy->isAbstract())
122 OldTy->removeAbstractTypeUser(this);
123
124 // Don't reinsert into the map if the key is concrete now.
125 if (NewTy->isAbstract())
126 insert(NewTy, DstTy);
127 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000128
Chris Lattner62a81a12008-06-16 21:00:18 +0000129 /// The other case which AbstractTypeUsers must be aware of is when a type
130 /// makes the transition from being abstract (where it has clients on it's
131 /// AbstractTypeUsers list) to concrete (where it does not). This method
132 /// notifies ATU's when this occurs for a type.
133 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
134 TheMap.erase(AbsTy);
135 AbsTy->removeAbstractTypeUser(this);
136 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000137
Chris Lattner62a81a12008-06-16 21:00:18 +0000138 // for debugging...
139 virtual void dump() const {
David Greene0fbf0e32010-01-05 01:27:59 +0000140 dbgs() << "AbstractTypeSet!\n";
Chris Lattner62a81a12008-06-16 21:00:18 +0000141 }
142};
143}
144
145
Chris Lattnere76c57a2003-08-22 06:07:12 +0000146// RecursiveResolveTypes - This is just like ResolveTypes, except that it
147// recurses down into derived types, merging the used types if the parent types
148// are compatible.
Chris Lattnera4477f92008-06-16 21:17:12 +0000149static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner62a81a12008-06-16 21:00:18 +0000150 LinkerTypeMap &Pointers) {
Chris Lattnera4477f92008-06-16 21:17:12 +0000151 if (DstTy == SrcTy) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +0000152
Chris Lattnere76c57a2003-08-22 06:07:12 +0000153 // If we found our opaque type, resolve it now!
Duncan Sands47c51882010-02-16 14:50:09 +0000154 if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy())
Chris Lattnera4477f92008-06-16 21:17:12 +0000155 return ResolveTypes(DstTy, SrcTy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000156
Chris Lattnere76c57a2003-08-22 06:07:12 +0000157 // Two types cannot be resolved together if they are of different primitive
158 // type. For example, we cannot resolve an int to a float.
Chris Lattnera4477f92008-06-16 21:17:12 +0000159 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000160
Chris Lattner56539652008-06-16 20:03:01 +0000161 // If neither type is abstract, then they really are just different types.
Chris Lattnera4477f92008-06-16 21:17:12 +0000162 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattner56539652008-06-16 20:03:01 +0000163 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000164
Chris Lattnere76c57a2003-08-22 06:07:12 +0000165 // Otherwise, resolve the used type used by this derived type...
Chris Lattnera4477f92008-06-16 21:17:12 +0000166 switch (DstTy->getTypeID()) {
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000167 default:
168 return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000169 case Type::FunctionTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000170 const FunctionType *DstFT = cast<FunctionType>(DstTy);
171 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000172 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
173 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000174 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000175
Chris Lattnera4477f92008-06-16 21:17:12 +0000176 // Use TypeHolder's so recursive resolution won't break us.
177 PATypeHolder ST(SrcFT), DT(DstFT);
178 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
179 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
180 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000181 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000182 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000183 return false;
184 }
185 case Type::StructTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000186 const StructType *DstST = cast<StructType>(DstTy);
187 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000188 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000189 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000190
Chris Lattnera4477f92008-06-16 21:17:12 +0000191 PATypeHolder ST(SrcST), DT(DstST);
192 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
193 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
194 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000195 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000196 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000197 return false;
198 }
199 case Type::ArrayTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000200 const ArrayType *DAT = cast<ArrayType>(DstTy);
201 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000202 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000203 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000204 Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000205 }
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000206 case Type::VectorTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000207 const VectorType *DVT = cast<VectorType>(DstTy);
208 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000209 if (DVT->getNumElements() != SVT->getNumElements()) return true;
210 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
211 Pointers);
212 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000213 case Type::PointerTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000214 const PointerType *DstPT = cast<PointerType>(DstTy);
215 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000216
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000217 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
218 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000219
Chris Lattnere3092c92003-08-23 21:25:54 +0000220 // If this is a pointer type, check to see if we have already seen it. If
221 // so, we are in a recursive branch. Cut off the search now. We cannot use
222 // an associative container for this search, because the type pointers (keys
Chris Lattner62a81a12008-06-16 21:00:18 +0000223 // in the container) change whenever types get resolved.
224 if (SrcPT->isAbstract())
225 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
226 return ExistingDestTy != DstPT;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000227
Chris Lattner62a81a12008-06-16 21:00:18 +0000228 if (DstPT->isAbstract())
229 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
230 return ExistingSrcTy != SrcPT;
Chris Lattnere3092c92003-08-23 21:25:54 +0000231 // Otherwise, add the current pointers to the vector to stop recursion on
232 // this pair.
Chris Lattner62a81a12008-06-16 21:00:18 +0000233 if (DstPT->isAbstract())
234 Pointers.insert(DstPT, SrcPT);
235 if (SrcPT->isAbstract())
236 Pointers.insert(SrcPT, DstPT);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000237
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000238 return RecursiveResolveTypesI(DstPT->getElementType(),
239 SrcPT->getElementType(), Pointers);
Chris Lattnere3092c92003-08-23 21:25:54 +0000240 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000241 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000242}
243
Chris Lattnera4477f92008-06-16 21:17:12 +0000244static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner62a81a12008-06-16 21:00:18 +0000245 LinkerTypeMap PointerTypes;
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000246 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Chris Lattnere3092c92003-08-23 21:25:54 +0000247}
248
Chris Lattnere76c57a2003-08-22 06:07:12 +0000249
Chris Lattner2c236f32001-11-03 05:18:24 +0000250// LinkTypes - Go through the symbol table of the Src module and see if any
251// types are named in the src module that are not named in the Dst module.
252// Make sure there are no type name conflicts.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000253static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000254 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
255 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000256
257 // Look for a type plane for Type's...
Reid Spencer78d033e2007-01-06 07:24:44 +0000258 TypeSymbolTable::const_iterator TI = SrcST->begin();
259 TypeSymbolTable::const_iterator TE = SrcST->end();
Reid Spencer567bc2c2004-05-25 08:52:20 +0000260 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000261
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000262 // Some types cannot be resolved immediately because they depend on other
263 // types being resolved to each other first. This contains a list of types we
264 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000265 std::vector<std::string> DelayedTypesToResolve;
266
Reid Spencer567bc2c2004-05-25 08:52:20 +0000267 for ( ; TI != TE; ++TI ) {
268 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000269 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000270
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000271 // Check to see if this type name is already in the dest module.
Reid Spencer78d033e2007-01-06 07:24:44 +0000272 Type *Entry = DestST->lookup(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000273
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000274 // If the name is just in the source module, bring it over to the dest.
275 if (Entry == 0) {
276 if (!Name.empty())
277 DestST->insert(Name, const_cast<Type*>(RHS));
278 } else if (ResolveTypes(Entry, RHS)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000279 // They look different, save the types 'till later to resolve.
280 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000281 }
282 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000283
284 // Iteratively resolve types while we can...
285 while (!DelayedTypesToResolve.empty()) {
286 // Loop over all of the types, attempting to resolve them if possible...
287 unsigned OldSize = DelayedTypesToResolve.size();
288
Chris Lattnere76c57a2003-08-22 06:07:12 +0000289 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000290 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
291 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000292 Type *T1 = SrcST->lookup(Name);
293 Type *T2 = DestST->lookup(Name);
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000294 if (!ResolveTypes(T2, T1)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000295 // We are making progress!
296 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
297 --i;
298 }
299 }
300
301 // Did we not eliminate any types?
302 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000303 // Attempt to resolve subelements of types. This allows us to merge these
304 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000305 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
306 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnera4477f92008-06-16 21:17:12 +0000307 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000308 // We are making progress!
309 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000310
Chris Lattnere76c57a2003-08-22 06:07:12 +0000311 // Go back to the main loop, perhaps we can resolve directly by name
312 // now...
313 break;
314 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000315 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000316
317 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000318 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000319 // Remove the symbol name from the destination.
320 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000321 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000322 }
323 }
324
325
Chris Lattner2c236f32001-11-03 05:18:24 +0000326 return false;
327}
328
Reid Spencer8bef0372007-02-04 04:29:21 +0000329/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
330/// in the symbol table. This is good for all clients except for us. Go
331/// through the trouble to force this back.
Chris Lattnerc0036282004-08-04 07:05:54 +0000332static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
333 assert(GV->getName() != Name && "Can't force rename to self");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000334 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
Chris Lattnerc0036282004-08-04 07:05:54 +0000335
336 // If there is a conflict, rename the conflict.
Chris Lattner33f29492007-02-11 00:39:38 +0000337 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000338 assert(ConflictGV->hasLocalLinkage() &&
Reid Spenceref9b9a72007-02-05 20:47:22 +0000339 "Not conflicting with a static global, should link instead!");
Chris Lattner33f29492007-02-11 00:39:38 +0000340 GV->takeName(ConflictGV);
341 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Reid Spenceref9b9a72007-02-05 20:47:22 +0000342 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000343 } else {
344 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000345 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000346}
Reid Spencer8bef0372007-02-04 04:29:21 +0000347
Reid Spenceref9b9a72007-02-05 20:47:22 +0000348/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000349/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000350static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000351 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
352 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
353 DestGV->copyAttributesFrom(SrcGV);
354 DestGV->setAlignment(Alignment);
Rafael Espindolac2a94da2011-01-13 05:12:34 +0000355 if (SrcGV->hasUnnamedAddr())
356 DestGV->setUnnamedAddr(true);
Chris Lattnerc0036282004-08-04 07:05:54 +0000357}
358
Chris Lattneraee38ea2004-12-03 22:18:41 +0000359/// GetLinkageResult - This analyzes the two global values and determines what
360/// the result will look like in the destination module. In particular, it
361/// computes the resultant linkage type, computes whether the global in the
362/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000363/// one), and computes whether this linkage is an error or not. It also performs
364/// visibility checks: we cannot link together two symbols with different
365/// visibilities.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000366static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Chris Lattneraee38ea2004-12-03 22:18:41 +0000367 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
368 std::string *Err) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000369 assert((!Dest || !Src->hasLocalLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000370 "If Src has internal linkage, Dest shouldn't be set!");
371 if (!Dest) {
372 // Linking something to nothing.
373 LinkFromSrc = true;
374 LT = Src->getLinkage();
Reid Spencer5cbf9852007-01-30 20:08:39 +0000375 } else if (Src->isDeclaration()) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000376 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000377 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000378 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000379 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000380 if (Dest->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000381 LinkFromSrc = true;
382 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000383 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000384 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000385 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000386 LinkFromSrc = true;
387 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000388 } else {
389 LinkFromSrc = false;
390 LT = Dest->getLinkage();
391 }
Reid Spencer5cbf9852007-01-30 20:08:39 +0000392 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000393 // If Dest is external but Src is not:
394 LinkFromSrc = true;
395 LT = Src->getLinkage();
396 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
397 if (Src->getLinkage() != Dest->getLinkage())
398 return Error(Err, "Linking globals named '" + Src->getName() +
399 "': can only link appending global with another appending global!");
400 LinkFromSrc = true; // Special cased.
401 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000402 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000403 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
404 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000405 if (Dest->hasExternalWeakLinkage() ||
406 Dest->hasAvailableExternallyLinkage() ||
407 (Dest->hasLinkOnceLinkage() &&
408 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000409 LinkFromSrc = true;
410 LT = Src->getLinkage();
411 } else {
412 LinkFromSrc = false;
413 LT = Dest->getLinkage();
414 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000415 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000416 // At this point we know that Src has External* or DLL* linkage.
417 if (Src->hasExternalWeakLinkage()) {
418 LinkFromSrc = false;
419 LT = Dest->getLinkage();
420 } else {
421 LinkFromSrc = true;
422 LT = GlobalValue::ExternalLinkage;
423 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000424 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000425 assert((Dest->hasExternalLinkage() ||
426 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000427 Dest->hasDLLExportLinkage() ||
428 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000429 (Src->hasExternalLinkage() ||
430 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000431 Src->hasDLLExportLinkage() ||
432 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000433 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000434 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000435 "': symbol multiply defined!");
436 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000437
438 // Check visibility
439 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattner97f8b092007-08-19 22:22:54 +0000440 if (!Src->isDeclaration() && !Dest->isDeclaration())
441 return Error(Err, "Linking globals named '" + Src->getName() +
442 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000443 return false;
444}
Chris Lattner5c377c52001-10-14 23:29:15 +0000445
Devang Patelab67e702009-08-11 18:01:24 +0000446// Insert all of the named mdnoes in Src into the Dest module.
Dan Gohmane5835fb2010-08-24 19:31:04 +0000447static void LinkNamedMDNodes(Module *Dest, Module *Src,
448 ValueToValueMapTy &ValueMap) {
Devang Patelab67e702009-08-11 18:01:24 +0000449 for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
450 E = Src->named_metadata_end(); I != E; ++I) {
451 const NamedMDNode *SrcNMD = I;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000452 NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName());
453 // Add Src elements into Dest node.
Michael J. Spencer79e86252010-12-18 22:23:15 +0000454 for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
Dan Gohmane5835fb2010-08-24 19:31:04 +0000455 DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i),
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000456 ValueMap)));
Devang Patelab67e702009-08-11 18:01:24 +0000457 }
458}
459
Chris Lattner5c377c52001-10-14 23:29:15 +0000460// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000461// them into the dest module.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000462static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000463 ValueToValueMapTy &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000464 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000465 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000466 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000467
Chris Lattner5c377c52001-10-14 23:29:15 +0000468 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner0bb87572008-07-14 05:52:33 +0000469 for (Module::const_global_iterator I = Src->global_begin(),
470 E = Src->global_end(); I != E; ++I) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000471 const GlobalVariable *SGV = I;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000472 GlobalValue *DGV = 0;
473
Bill Wendling933f9bd2010-10-06 20:18:44 +0000474 // Check to see if may have to link the global with the global, alias or
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000475 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000476 if (SGV->hasName() && !SGV->hasLocalLinkage())
Bill Wendling933f9bd2010-10-06 20:18:44 +0000477 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000478
Chris Lattnerae1132d2008-07-14 06:52:19 +0000479 // If we found a global with the same name in the dest module, but it has
480 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000481 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000482 DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000483
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000484 // If types don't agree due to opaque types, try to resolve them.
485 if (DGV && DGV->getType() != SGV->getType())
486 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000487
Dan Gohmanc3183292007-10-08 15:13:30 +0000488 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
489 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000490 "Global must either be external or have an initializer!");
491
Chris Lattnerb324bd72006-11-09 05:18:12 +0000492 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
493 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000494 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
495 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000496
Chris Lattner6157e382008-07-14 07:23:24 +0000497 if (DGV == 0) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000498 // No linking to be performed, simply create an identical version of the
499 // symbol over in the dest module... the initializer will be filled in
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000500 // later by LinkGlobalInits.
Chris Lattner2719bac2003-04-21 21:15:04 +0000501 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000502 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Chris Lattner2719bac2003-04-21 21:15:04 +0000503 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000504 SGV->getName(), 0, false,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000505 SGV->getType()->getAddressSpace());
Reid Spencer471feac2007-02-04 04:30:33 +0000506 // Propagate alignment, visibility and section info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000507 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000508
Chris Lattner2719bac2003-04-21 21:15:04 +0000509 // If the LLVM runtime renamed the global, but it is an externally visible
510 // symbol, DGV must be an existing global with internal linkage. Rename
511 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000512 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
Chris Lattnerc0036282004-08-04 07:05:54 +0000513 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000514
Chris Lattner6157e382008-07-14 07:23:24 +0000515 // Make sure to remember this mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000516 ValueMap[SGV] = NewDGV;
517
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000518 // Keep track that this is an appending variable.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000519 if (SGV->hasAppendingLinkage())
Chris Lattner8166e6e2003-05-13 21:33:43 +0000520 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000521 continue;
522 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000523
Chris Lattner6157e382008-07-14 07:23:24 +0000524 // If the visibilities of the symbols disagree and the destination is a
525 // prototype, take the visibility of its input.
526 if (DGV->isDeclaration())
527 DGV->setVisibility(SGV->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000528
Chris Lattner6157e382008-07-14 07:23:24 +0000529 if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000530 // No linking is performed yet. Just insert a new copy of the global, and
531 // keep track of the fact that it is an appending variable in the
532 // AppendingVars map. The name is cleared out so that no linkage is
533 // performed.
534 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000535 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Chris Lattner8166e6e2003-05-13 21:33:43 +0000536 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000537 "", 0, false,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000538 SGV->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +0000539
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000540 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000541 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000542 // Propagate alignment, section and visibility info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000543 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000544
Chris Lattner8166e6e2003-05-13 21:33:43 +0000545 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000546 ValueMap[SGV] = NewDGV;
Chris Lattner8166e6e2003-05-13 21:33:43 +0000547
548 // Keep track that this is an appending variable...
549 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000550 continue;
551 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000552
Chris Lattner6157e382008-07-14 07:23:24 +0000553 if (LinkFromSrc) {
554 if (isa<GlobalAlias>(DGV))
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000555 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
556 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000557
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000558 // If the types don't match, and if we are to link from the source, nuke
559 // DGV and create a new one of the appropriate type. Note that the thing
560 // we are replacing may be a function (if a prototype, weak, etc) or a
561 // global variable.
562 GlobalVariable *NewDGV =
Michael J. Spencer79e86252010-12-18 22:23:15 +0000563 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
564 SGV->isConstant(), NewLinkage, /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000565 DGV->getName(), 0, false,
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000566 SGV->getType()->getAddressSpace());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000567
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000568 // Propagate alignment, section, and visibility info.
569 CopyGVAttributes(NewDGV, SGV);
Michael J. Spencer79e86252010-12-18 22:23:15 +0000570 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000571 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000572
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000573 // DGV will conflict with NewDGV because they both had the same
574 // name. We must erase this now so ForceRenaming doesn't assert
575 // because DGV might not have internal linkage.
576 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
577 Var->eraseFromParent();
578 else
579 cast<Function>(DGV)->eraseFromParent();
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000580
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000581 // If the symbol table renamed the global, but it is an externally visible
582 // symbol, DGV must be an existing global with internal linkage. Rename.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000583 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000584 ForceRenaming(NewDGV, SGV->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000585
Chris Lattner6157e382008-07-14 07:23:24 +0000586 // Inherit const as appropriate.
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000587 NewDGV->setConstant(SGV->isConstant());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000588
Chris Lattner6157e382008-07-14 07:23:24 +0000589 // Make sure to remember this mapping.
590 ValueMap[SGV] = NewDGV;
591 continue;
Chris Lattner5c377c52001-10-14 23:29:15 +0000592 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000593
Chris Lattner6157e382008-07-14 07:23:24 +0000594 // Not "link from source", keep the one in the DestModule and remap the
595 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000596
Chris Lattner6157e382008-07-14 07:23:24 +0000597 // Special case for const propagation.
598 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
599 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
600 DGVar->setConstant(true);
601
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000602 // SGV is global, but DGV is alias.
603 if (isa<GlobalAlias>(DGV)) {
604 // The only valid mappings are:
605 // - SGV is external declaration, which is effectively a no-op.
606 // - SGV is weak, when we just need to throw SGV out.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000607 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000608 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
609 "': symbol multiple defined");
610 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000611
Chris Lattner6157e382008-07-14 07:23:24 +0000612 // Set calculated linkage
613 DGV->setLinkage(NewLinkage);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000614
Chris Lattner6157e382008-07-14 07:23:24 +0000615 // Make sure to remember this mapping...
Owen Andersonbaf3c402009-07-29 18:55:55 +0000616 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000617 }
618 return false;
619}
620
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000621static GlobalValue::LinkageTypes
622CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000623 GlobalValue::LinkageTypes SL = SGV->getLinkage();
624 GlobalValue::LinkageTypes DL = DGV->getLinkage();
625 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000626 return GlobalValue::ExternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +0000627 else if (SL == GlobalValue::WeakAnyLinkage ||
628 DL == GlobalValue::WeakAnyLinkage)
629 return GlobalValue::WeakAnyLinkage;
630 else if (SL == GlobalValue::WeakODRLinkage ||
631 DL == GlobalValue::WeakODRLinkage)
632 return GlobalValue::WeakODRLinkage;
633 else if (SL == GlobalValue::InternalLinkage &&
634 DL == GlobalValue::InternalLinkage)
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000635 return GlobalValue::InternalLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000636 else if (SL == GlobalValue::LinkerPrivateLinkage &&
637 DL == GlobalValue::LinkerPrivateLinkage)
638 return GlobalValue::LinkerPrivateLinkage;
Bill Wendling4e34d502010-08-24 20:00:52 +0000639 else if (SL == GlobalValue::LinkerPrivateWeakLinkage &&
640 DL == GlobalValue::LinkerPrivateWeakLinkage)
641 return GlobalValue::LinkerPrivateWeakLinkage;
642 else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage &&
643 DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage)
644 return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000645 else {
Duncan Sands667d4b82009-03-07 15:45:40 +0000646 assert (SL == GlobalValue::PrivateLinkage &&
647 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
Rafael Espindolabb46f522009-01-15 20:18:42 +0000648 return GlobalValue::PrivateLinkage;
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000649 }
650}
651
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000652// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000653// dest module. We're assuming, that all functions/global variables were already
654// linked in.
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000655static bool LinkAlias(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000656 ValueToValueMapTy &ValueMap,
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000657 std::string *Err) {
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000658 // Loop over all alias in the src module
659 for (Module::const_alias_iterator I = Src->alias_begin(),
660 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000661 const GlobalAlias *SGA = I;
662 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
663 GlobalAlias *NewGA = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000664
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000665 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000666 // of SAliasee in Dest.
Dan Gohman05ea54e2010-08-24 18:50:07 +0000667 ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee);
Ted Kremenek58d5e052008-03-09 18:32:50 +0000668 assert(VMI != ValueMap.end() && "Aliasee not linked");
669 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000670 GlobalValue* DGV = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000671
Rafael Espindola19785992010-10-19 02:02:57 +0000672 // Fixup aliases to bitcasts. Note that aliases to GEPs are still broken
673 // by this, but aliases to GEPs are broken to a lot of other things, so
674 // it's less important.
675 Constant *DAliaseeConst = DAliasee;
676 if (SGA->getType() != DAliasee->getType())
677 DAliaseeConst = ConstantExpr::getBitCast(DAliasee, SGA->getType());
678
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000679 // Try to find something 'similar' to SGA in destination module.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000680 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000681 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000682
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000683 // If types don't agree due to opaque types, try to resolve them.
684 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000685 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000686 }
687
Rafael Espindolabb46f522009-01-15 20:18:42 +0000688 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000689 DGV = Dest->getGlobalVariable(SGA->getName());
690
691 // If types don't agree due to opaque types, try to resolve them.
692 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000693 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000694 }
695
Rafael Espindolabb46f522009-01-15 20:18:42 +0000696 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000697 DGV = Dest->getFunction(SGA->getName());
698
699 // If types don't agree due to opaque types, try to resolve them.
700 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner5ed2ba22008-07-10 01:09:33 +0000701 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000702 }
703
704 // No linking to be performed on internal stuff.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000705 if (DGV && DGV->hasLocalLinkage())
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000706 DGV = NULL;
707
708 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
709 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000710 // globals are already linked we just need query ValueMap to find the
711 // mapping.
712 if (DAliasee == DGA->getAliasedGlobal()) {
713 // This is just two copies of the same alias. Propagate linkage, if
714 // necessary.
715 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
716
717 NewGA = DGA;
718 // Proceed to 'common' steps
719 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000720 return Error(Err, "Alias Collision on '" + SGA->getName()+
721 "': aliases have different aliasees");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000722 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000723 // The only allowed way is to link alias with external declaration or weak
724 // symbol..
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000725 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000726 // But only if aliasee is global too...
727 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000728 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
729 "': aliasee is not global variable");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000730
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000731 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
Rafael Espindola19785992010-10-19 02:02:57 +0000732 SGA->getName(), DAliaseeConst, Dest);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000733 CopyGVAttributes(NewGA, SGA);
734
735 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000736 if (SGA->getType() != DGVar->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000737 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000738 DGVar->getType()));
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000739 else
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000740 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000741
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000742 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000743 // name. We must erase this now so ForceRenaming doesn't assert
744 // because DGV might not have internal linkage.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000745 DGVar->eraseFromParent();
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000746
747 // Proceed to 'common' steps
748 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000749 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
750 "': symbol multiple defined");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000751 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000752 // The only allowed way is to link alias with external declaration or weak
753 // symbol...
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000754 if (DF->isDeclaration() || DF->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000755 // But only if aliasee is function too...
756 if (!isa<Function>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000757 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
758 "': aliasee is not function");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000759
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000760 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
Rafael Espindola19785992010-10-19 02:02:57 +0000761 SGA->getName(), DAliaseeConst, Dest);
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000762 CopyGVAttributes(NewGA, SGA);
763
764 // Any uses of DF need to change to NewGA, with cast, if needed.
765 if (SGA->getType() != DF->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000766 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000767 DF->getType()));
768 else
769 DF->replaceAllUsesWith(NewGA);
770
771 // DF will conflict with NewGA because they both had the same
772 // name. We must erase this now so ForceRenaming doesn't assert
773 // because DF might not have internal linkage.
774 DF->eraseFromParent();
775
776 // Proceed to 'common' steps
777 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000778 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
779 "': symbol multiple defined");
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000780 } else {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000781 // No linking to be performed, simply create an identical version of the
782 // alias over in the dest module...
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000783 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
Rafael Espindola19785992010-10-19 02:02:57 +0000784 SGA->getName(), DAliaseeConst, Dest);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000785 CopyGVAttributes(NewGA, SGA);
786
787 // Proceed to 'common' steps
788 }
789
790 assert(NewGA && "No alias was created in destination module!");
791
Anton Korobeynikovb8cdaf72008-03-10 22:36:35 +0000792 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000793 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000794 if (NewGA->getName() != SGA->getName() &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000795 !NewGA->hasLocalLinkage())
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000796 ForceRenaming(NewGA, SGA->getName());
797
798 // Remember this mapping so uses in the source module get remapped
Dan Gohman05ea54e2010-08-24 18:50:07 +0000799 // later by MapValue.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000800 ValueMap[SGA] = NewGA;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000801 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000802
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000803 return false;
804}
805
Chris Lattner5c377c52001-10-14 23:29:15 +0000806
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000807// LinkGlobalInits - Update the initializers in the Dest module now that all
808// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000809static bool LinkGlobalInits(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000810 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000811 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000812 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000813 for (Module::const_global_iterator I = Src->global_begin(),
814 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000815 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000816
817 if (SGV->hasInitializer()) { // Only process initialized GV's
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000818 // Figure out what the initializer looks like in the dest module.
Chris Lattner4ad02e72003-04-16 20:28:45 +0000819 Constant *SInit =
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000820 cast<Constant>(MapValue(SGV->getInitializer(), ValueMap));
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000821 // Grab destination global variable or alias.
822 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000823
Bill Wendling933f9bd2010-10-06 20:18:44 +0000824 // If dest if global variable, check that initializers match.
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000825 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
826 if (DGVar->hasInitializer()) {
Bill Wendling933f9bd2010-10-06 20:18:44 +0000827 if (SGV->hasExternalLinkage()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000828 if (DGVar->getInitializer() != SInit)
829 return Error(Err, "Global Variable Collision on '" +
830 SGV->getName() +
831 "': global variables have different initializers");
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000832 } else if (DGVar->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000833 // Nothing is required, mapped values will take the new global
834 // automatically.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000835 } else if (SGV->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000836 // Nothing is required, mapped values will take the new global
837 // automatically.
838 } else if (DGVar->hasAppendingLinkage()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000839 llvm_unreachable("Appending linkage unimplemented!");
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000840 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000841 llvm_unreachable("Unknown linkage!");
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000842 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000843 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000844 // Copy the initializer over now...
845 DGVar->setInitializer(SInit);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000846 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000847 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000848 // Destination is alias, the only valid situation is when source is
849 // weak. Also, note, that we already checked linkage in LinkGlobals(),
850 // thus we assert here.
851 // FIXME: Should we weaken this assumption, 'dereference' alias and
852 // check for initializer of aliasee?
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000853 assert(SGV->isWeakForLinker());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000854 }
855 }
856 }
857 return false;
858}
Chris Lattner5c377c52001-10-14 23:29:15 +0000859
Chris Lattner79df7c02002-03-26 18:01:55 +0000860// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000861// without doing function bodies... this just adds external function prototypes
862// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000863//
Chris Lattner79df7c02002-03-26 18:01:55 +0000864static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000865 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000866 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000867 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000868
Reid Spencer619f0242007-02-04 04:43:17 +0000869 // Loop over all of the functions in the src module, mapping them over
Chris Lattner5c377c52001-10-14 23:29:15 +0000870 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000871 const Function *SF = I; // SrcFunction
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000872 GlobalValue *DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000873
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000874 // Check to see if may have to link the function with the global, alias or
875 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000876 if (SF->hasName() && !SF->hasLocalLinkage())
Daniel Dunbar03d76512009-07-25 23:55:21 +0000877 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000878
Chris Lattnerae1132d2008-07-14 06:52:19 +0000879 // If we found a global with the same name in the dest module, but it has
880 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000881 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000882 DGV = 0;
883
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000884 // If types don't agree due to opaque types, try to resolve them.
885 if (DGV && DGV->getType() != SF->getType())
886 RecursiveResolveTypes(SF->getType(), DGV->getType());
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000887
Chris Lattner6157e382008-07-14 07:23:24 +0000888 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
889 bool LinkFromSrc = false;
890 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
891 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000892
Chris Lattner82468492008-06-09 07:36:11 +0000893 // If there is no linkage to be performed, just bring over SF without
894 // modifying it.
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000895 if (DGV == 0) {
Chris Lattner82468492008-06-09 07:36:11 +0000896 // Function does not already exist, simply insert an function signature
897 // identical to SF into the dest module.
898 Function *NewDF = Function::Create(SF->getFunctionType(),
899 SF->getLinkage(),
900 SF->getName(), Dest);
901 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000902
Chris Lattner82468492008-06-09 07:36:11 +0000903 // If the LLVM runtime renamed the function, but it is an externally
904 // visible symbol, DF must be an existing function with internal linkage.
905 // Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000906 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
Chris Lattner82468492008-06-09 07:36:11 +0000907 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000908
Chris Lattner82468492008-06-09 07:36:11 +0000909 // ... and remember this mapping...
910 ValueMap[SF] = NewDF;
911 continue;
Chris Lattner6157e382008-07-14 07:23:24 +0000912 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000913
Chris Lattner6157e382008-07-14 07:23:24 +0000914 // If the visibilities of the symbols disagree and the destination is a
915 // prototype, take the visibility of its input.
916 if (DGV->isDeclaration())
917 DGV->setVisibility(SF->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000918
Chris Lattner6157e382008-07-14 07:23:24 +0000919 if (LinkFromSrc) {
920 if (isa<GlobalAlias>(DGV))
921 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
922 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000923
Chris Lattner6157e382008-07-14 07:23:24 +0000924 // We have a definition of the same name but different type in the
925 // source module. Copy the prototype to the destination and replace
926 // uses of the destination's prototype with the new prototype.
927 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
928 SF->getName(), Dest);
929 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000930
Chris Lattner6157e382008-07-14 07:23:24 +0000931 // Any uses of DF need to change to NewDF, with cast
Michael J. Spencer79e86252010-12-18 22:23:15 +0000932 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000933 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000934
Chris Lattner6157e382008-07-14 07:23:24 +0000935 // DF will conflict with NewDF because they both had the same. We must
936 // erase this now so ForceRenaming doesn't assert because DF might
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000937 // not have internal linkage.
Chris Lattner6157e382008-07-14 07:23:24 +0000938 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
939 Var->eraseFromParent();
940 else
941 cast<Function>(DGV)->eraseFromParent();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000942
Chris Lattner6157e382008-07-14 07:23:24 +0000943 // If the symbol table renamed the function, but it is an externally
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000944 // visible symbol, DF must be an existing function with internal
Chris Lattner6157e382008-07-14 07:23:24 +0000945 // linkage. Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000946 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
Chris Lattner6157e382008-07-14 07:23:24 +0000947 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000948
Chris Lattner6157e382008-07-14 07:23:24 +0000949 // Remember this mapping so uses in the source module get remapped
Dan Gohman05ea54e2010-08-24 18:50:07 +0000950 // later by MapValue.
Chris Lattner6157e382008-07-14 07:23:24 +0000951 ValueMap[SF] = NewDF;
952 continue;
953 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000954
Chris Lattner6157e382008-07-14 07:23:24 +0000955 // Not "link from source", keep the one in the DestModule and remap the
956 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000957
Chris Lattner6157e382008-07-14 07:23:24 +0000958 if (isa<GlobalAlias>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000959 // The only valid mappings are:
960 // - SF is external declaration, which is effectively a no-op.
961 // - SF is weak, when we just need to throw SF out.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000962 if (!SF->isDeclaration() && !SF->isWeakForLinker())
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000963 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
964 "': symbol multiple defined");
Chris Lattner82468492008-06-09 07:36:11 +0000965 }
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000966
Chris Lattner6157e382008-07-14 07:23:24 +0000967 // Set calculated linkage
968 DGV->setLinkage(NewLinkage);
Chris Lattner5c377c52001-10-14 23:29:15 +0000969
Chris Lattner6157e382008-07-14 07:23:24 +0000970 // Make sure to remember this mapping.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000971 ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000972 }
973 return false;
974}
975
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000976// LinkFunctionBody - Copy the source function over into the dest function and
977// fix up references to values. At this point we know that Dest is an external
978// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000979static bool LinkFunctionBody(Function *Dest, Function *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +0000980 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000981 std::string *Err) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000982 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000983
Chris Lattner0033baf2004-11-16 17:12:38 +0000984 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +0000985 Function::arg_iterator DI = Dest->arg_begin();
986 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000987 I != E; ++I, ++DI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000988 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000989
990 // Add a mapping to our local map
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000991 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000992 }
993
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000994 // Splice the body of the source function into the dest function.
995 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +0000996
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000997 // At this point, all of the instructions and values of the function are now
998 // copied over. The only problem is that they are still referencing values in
999 // the Source function as operands. Loop through all of the operands of the
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +00001000 // functions and patch them up to point to the local versions.
Chris Lattner18961502002-06-25 16:12:52 +00001001 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +00001002 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1003 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries);
Chris Lattner0033baf2004-11-16 17:12:38 +00001004
1005 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +00001006 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1007 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +00001008 ValueMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +00001009
1010 return false;
1011}
1012
1013
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001014// LinkFunctionBodies - Link in the function bodies that are defined in the
1015// source module into the DestModule. This consists basically of copying the
1016// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001017static bool LinkFunctionBodies(Module *Dest, Module *Src,
Dan Gohman05ea54e2010-08-24 18:50:07 +00001018 ValueToValueMapTy &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001019 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +00001020
Reid Spencer8bef0372007-02-04 04:29:21 +00001021 // Loop over all of the functions in the src module, mapping them over as we
1022 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001023 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer619f0242007-02-04 04:43:17 +00001024 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001025 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +00001026
Chris Lattner18961502002-06-25 16:12:52 +00001027 // DF not external SF external?
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001028 if (DF && DF->isDeclaration())
Chris Lattner35956552003-10-27 16:39:39 +00001029 // Only provide the function body if there isn't one already.
1030 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1031 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +00001032 }
Chris Lattner5c377c52001-10-14 23:29:15 +00001033 }
1034 return false;
1035}
1036
Chris Lattner8166e6e2003-05-13 21:33:43 +00001037// LinkAppendingVars - If there were any appending global variables, link them
1038// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001039static bool LinkAppendingVars(Module *M,
1040 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1041 std::string *ErrorMsg) {
1042 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +00001043
Chris Lattner8166e6e2003-05-13 21:33:43 +00001044 // Loop over the multimap of appending vars, processing any variables with the
1045 // same name, forming a new appending global variable with both of the
1046 // initializers merged together, then rewrite references to the old variables
1047 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001048 std::vector<Constant*> Inits;
1049 while (AppendingVars.size() > 1) {
1050 // Get the first two elements in the map...
1051 std::multimap<std::string,
1052 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1053
1054 // If the first two elements are for different names, there is no pair...
1055 // Otherwise there is a pair, so link them together...
1056 if (First->first == Second->first) {
1057 GlobalVariable *G1 = First->second, *G2 = Second->second;
1058 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1059 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +00001060
Chris Lattner8166e6e2003-05-13 21:33:43 +00001061 // Check to see that they two arrays agree on type...
1062 if (T1->getElementType() != T2->getElementType())
1063 return Error(ErrorMsg,
1064 "Appending variables with different element types need to be linked!");
1065 if (G1->isConstant() != G2->isConstant())
1066 return Error(ErrorMsg,
1067 "Appending variables linked with different const'ness!");
1068
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001069 if (G1->getAlignment() != G2->getAlignment())
1070 return Error(ErrorMsg,
1071 "Appending variables with different alignment need to be linked!");
1072
1073 if (G1->getVisibility() != G2->getVisibility())
1074 return Error(ErrorMsg,
1075 "Appending variables with different visibility need to be linked!");
1076
1077 if (G1->getSection() != G2->getSection())
1078 return Error(ErrorMsg,
1079 "Appending variables with different section name need to be linked!");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001080
Chris Lattner8166e6e2003-05-13 21:33:43 +00001081 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
Michael J. Spencer79e86252010-12-18 22:23:15 +00001082 ArrayType *NewType = ArrayType::get(T1->getElementType(),
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001083 NewSize);
Chris Lattner8166e6e2003-05-13 21:33:43 +00001084
Chris Lattnered74a4e2005-12-06 17:30:58 +00001085 G1->setName(""); // Clear G1's name in case of a conflict!
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001086
Chris Lattner8166e6e2003-05-13 21:33:43 +00001087 // Create the new global variable...
1088 GlobalVariable *NG =
Owen Andersone9b11b42009-07-08 19:03:57 +00001089 new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1090 /*init*/0, First->first, 0, G1->isThreadLocal(),
Chris Lattnera534b0f2008-06-27 03:10:24 +00001091 G1->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +00001092
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001093 // Propagate alignment, visibility and section info.
1094 CopyGVAttributes(NG, G1);
1095
Chris Lattner8166e6e2003-05-13 21:33:43 +00001096 // Merge the initializer...
1097 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +00001098 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1099 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001100 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001101 } else {
1102 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
Owen Andersona7235ea2009-07-31 20:28:14 +00001103 Constant *CV = Constant::getNullValue(T1->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001104 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1105 Inits.push_back(CV);
1106 }
1107 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1108 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001109 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001110 } else {
1111 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
Owen Andersona7235ea2009-07-31 20:28:14 +00001112 Constant *CV = Constant::getNullValue(T2->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001113 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1114 Inits.push_back(CV);
1115 }
Owen Anderson1fd70962009-07-28 18:32:17 +00001116 NG->setInitializer(ConstantArray::get(NewType, Inits));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001117 Inits.clear();
1118
1119 // Replace any uses of the two global variables with uses of the new
1120 // global...
1121
1122 // FIXME: This should rewrite simple/straight-forward uses such as
1123 // getelementptr instructions to not use the Cast!
Owen Andersonbaf3c402009-07-29 18:55:55 +00001124 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001125 G1->getType()));
Michael J. Spencer79e86252010-12-18 22:23:15 +00001126 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001127 G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001128
1129 // Remove the two globals from the module now...
1130 M->getGlobalList().erase(G1);
1131 M->getGlobalList().erase(G2);
1132
1133 // Put the new global into the AppendingVars map so that we can handle
1134 // linking of more than two vars...
1135 Second->second = NG;
1136 }
1137 AppendingVars.erase(First);
1138 }
1139
1140 return false;
1141}
Chris Lattner52f7e902001-10-13 07:03:50 +00001142
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001143static bool ResolveAliases(Module *Dest) {
1144 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov52419572008-03-11 22:51:09 +00001145 I != E; ++I)
David Chisnall34722462010-01-09 16:27:31 +00001146 // We can't sue resolveGlobalAlias here because we need to preserve
1147 // bitcasts and GEPs.
1148 if (const Constant *C = I->getAliasee()) {
1149 while (dyn_cast<GlobalAlias>(C))
1150 C = cast<GlobalAlias>(C)->getAliasee();
1151 const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1152 if (C != I && !(GV && GV->isDeclaration()))
1153 I->replaceAllUsesWith(const_cast<Constant*>(C));
1154 }
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001155
1156 return false;
1157}
Chris Lattner52f7e902001-10-13 07:03:50 +00001158
1159// LinkModules - This function links two modules together, with the resulting
1160// left module modified to be the composite of the two input modules. If an
1161// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001162// the problem. Upon failure, the Dest module could be in a modified state, and
1163// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +00001164bool
Reid Spencer0ba9e212004-12-13 03:00:16 +00001165Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +00001166 assert(Dest != 0 && "Invalid Destination module");
1167 assert(Src != 0 && "Invalid Source Module");
1168
Chris Lattnerc36357c2007-01-29 00:21:34 +00001169 if (Dest->getDataLayout().empty()) {
1170 if (!Src->getDataLayout().empty()) {
Chris Lattnerec9bfdc2007-01-29 02:18:13 +00001171 Dest->setDataLayout(Src->getDataLayout());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001172 } else {
1173 std::string DataLayout;
Reid Spencer26f23852007-01-26 08:11:39 +00001174
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001175 if (Dest->getEndianness() == Module::AnyEndianness) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001176 if (Src->getEndianness() == Module::BigEndian)
1177 DataLayout.append("E");
1178 else if (Src->getEndianness() == Module::LittleEndian)
1179 DataLayout.append("e");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001180 }
1181
1182 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001183 if (Src->getPointerSize() == Module::Pointer64)
1184 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1185 else if (Src->getPointerSize() == Module::Pointer32)
1186 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001187 }
Chris Lattnerc36357c2007-01-29 00:21:34 +00001188 Dest->setDataLayout(DataLayout);
1189 }
1190 }
1191
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001192 // Copy the target triple from the source to dest if the dest's is empty.
Chris Lattnerc36357c2007-01-29 00:21:34 +00001193 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
Chris Lattner152f19a2004-12-10 20:26:15 +00001194 Dest->setTargetTriple(Src->getTargetTriple());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001195
Chris Lattnerc36357c2007-01-29 00:21:34 +00001196 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1197 Src->getDataLayout() != Dest->getDataLayout())
Chris Lattnerbdff5482009-08-23 04:37:46 +00001198 errs() << "WARNING: Linking two modules of different data layouts!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +00001199 if (!Src->getTargetTriple().empty() &&
Chris Lattnera797ee02010-12-30 02:49:45 +00001200 Dest->getTargetTriple() != Src->getTargetTriple()) {
1201 errs() << "WARNING: Linking two modules of different target triples: ";
1202 if (!Src->getModuleIdentifier().empty())
1203 errs() << Src->getModuleIdentifier() << ": ";
1204 errs() << "'" << Src->getTargetTriple() << "' and '"
1205 << Dest->getTargetTriple() << "'\n";
1206 }
Misha Brukmanf976c852005-04-21 22:55:34 +00001207
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001208 // Append the module inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001209 if (!Src->getModuleInlineAsm().empty()) {
1210 if (Dest->getModuleInlineAsm().empty())
1211 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001212 else
Chris Lattner66316012006-01-24 04:14:29 +00001213 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1214 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001215 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001216
Reid Spencer719012d2004-11-25 09:29:44 +00001217 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +00001218 // from the source module. There's no opportunity for duplicates here as the
1219 // Module ensures that duplicate insertions are discarded.
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001220 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001221 SI != SE; ++SI)
Reid Spencer57a0efa2004-09-11 04:25:17 +00001222 Dest->addLibrary(*SI);
Reid Spencer57a0efa2004-09-11 04:25:17 +00001223
Chris Lattner2c236f32001-11-03 05:18:24 +00001224 // LinkTypes - Go through the symbol table of the Src module and see if any
1225 // types are named in the src module that are not named in the Dst module.
1226 // Make sure there are no type name conflicts.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001227 if (LinkTypes(Dest, Src, ErrorMsg))
Reid Spencer619f0242007-02-04 04:43:17 +00001228 return true;
Chris Lattner2c236f32001-11-03 05:18:24 +00001229
Chris Lattner5c377c52001-10-14 23:29:15 +00001230 // ValueMap - Mapping of values from what they used to be in Src, to what they
Dan Gohman05ea54e2010-08-24 18:50:07 +00001231 // are now in Dest. ValueToValueMapTy is a ValueMap, which involves some
1232 // overhead due to the use of Value handles which the Linker doesn't actually
1233 // need, but this allows us to reuse the ValueMapper code.
1234 ValueToValueMapTy ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +00001235
Chris Lattner8166e6e2003-05-13 21:33:43 +00001236 // AppendingVars - Keep track of global variables in the destination module
1237 // with appending linkage. After the module is linked together, they are
1238 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001239 std::multimap<std::string, GlobalVariable *> AppendingVars;
Chris Lattner11273152006-06-16 01:24:04 +00001240 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1241 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +00001242 // Add all of the appending globals already in the Dest module to
1243 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +00001244 if (I->hasAppendingLinkage())
1245 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner5a837de2004-08-04 07:44:58 +00001246 }
1247
Chris Lattner8166e6e2003-05-13 21:33:43 +00001248 // Insert all of the globals in src into the Dest module... without linking
1249 // initializers (which could refer to functions not yet mapped over).
Reid Spenceref9b9a72007-02-05 20:47:22 +00001250 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001251 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001252
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001253 // Link the functions together between the two modules, without doing function
1254 // bodies... this just adds external function prototypes to the Dest
1255 // function... We do this so that when we begin processing function bodies,
1256 // all of the global values that may be referenced are available in our
1257 // ValueMap.
Reid Spenceref9b9a72007-02-05 20:47:22 +00001258 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001259 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001260
Anton Korobeynikov4fb28732008-03-05 15:27:21 +00001261 // If there were any alias, link them now. We really need to do this now,
1262 // because all of the aliases that may be referenced need to be available in
1263 // ValueMap
1264 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1265
Chris Lattner6cdf1972002-07-18 00:13:08 +00001266 // Update the initializers in the Dest module now that all globals that may
1267 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +00001268 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1269
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001270 // Link in the function bodies that are defined in the source module into the
1271 // DestModule. This consists basically of copying the function over and
1272 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +00001273 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +00001274
Chris Lattner8166e6e2003-05-13 21:33:43 +00001275 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001276 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1277
Anton Korobeynikov3db91912008-03-05 23:08:47 +00001278 // Resolve all uses of aliases with aliasees
1279 if (ResolveAliases(Dest)) return true;
1280
Dan Gohmane422d1b2010-08-24 19:37:11 +00001281 // Remap all of the named mdnoes in Src into the Dest module. We do this
1282 // after linking GlobalValues so that MDNodes that reference GlobalValues
1283 // are properly remapped.
1284 LinkNamedMDNodes(Dest, Src, ValueMap);
1285
Reid Spencer57a0efa2004-09-11 04:25:17 +00001286 // If the source library's module id is in the dependent library list of the
1287 // destination library, remove it since that module is now linked in.
Michael J. Spencer73855092010-12-18 22:23:07 +00001288 const std::string &modId = Src->getModuleIdentifier();
1289 if (!modId.empty())
1290 Dest->removeLibrary(sys::path::stem(modId));
Reid Spencer57a0efa2004-09-11 04:25:17 +00001291
Chris Lattner52f7e902001-10-13 07:03:50 +00001292 return false;
1293}
Vikram S. Adve9466f512001-10-28 21:38:02 +00001294
Reid Spencer567bc2c2004-05-25 08:52:20 +00001295// vim: sw=2