blob: aa9a8fcafd478b97c39c470753e9b7c557258d76 [file] [log] [blame]
Chris Lattner52f7e902001-10-13 07:03:50 +00001//===- Linker.cpp - Module Linker Implementation --------------------------===//
2//
3// This file implements the LLVM module linker.
4//
5// Specifically, this:
Chris Lattner8d2de8a2001-10-15 03:12:52 +00006// * Merges global variables between the two modules
7// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00008// * Merges functions between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10//===----------------------------------------------------------------------===//
11
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000012#include "llvm/Transforms/Utils/Linker.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000013#include "llvm/Module.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000014#include "llvm/SymbolTable.h"
15#include "llvm/DerivedTypes.h"
16#include "llvm/iOther.h"
Chris Lattner31bcdb82002-04-28 19:55:58 +000017#include "llvm/Constants.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000018
19// Error - Simple wrapper function to conditionally assign to E and return true.
20// This just makes error return conditions a little bit simpler...
21//
Chris Lattner8166e6e2003-05-13 21:33:43 +000022static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000023 if (E) *E = Message;
24 return true;
25}
26
Chris Lattner4c00e532003-05-15 16:30:55 +000027// ResolveTypes - Attempt to link the two specified types together. Return true
28// if there is an error and they cannot yet be linked.
29//
Chris Lattnere76c57a2003-08-22 06:07:12 +000030static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
31 SymbolTable *DestST, const std::string &Name) {
32 if (DestTy == SrcTy) return false; // If already equal, noop
33
Chris Lattner4c00e532003-05-15 16:30:55 +000034 // Does the type already exist in the module?
35 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000036 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
37 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000038 } else {
39 return true; // Cannot link types... neither is opaque and not-equal
40 }
41 } else { // Type not in dest module. Add it now.
42 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000043 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
44 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000045 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000046 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000047 }
48 return false;
49}
50
Chris Lattner43f4ba82003-08-22 19:12:55 +000051static const FunctionType *getFT(const PATypeHolder &TH) {
52 return cast<FunctionType>(TH.get());
53}
Chris Lattner9732be72003-08-22 20:16:48 +000054static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000055 return cast<StructType>(TH.get());
56}
Chris Lattnere76c57a2003-08-22 06:07:12 +000057
58// RecursiveResolveTypes - This is just like ResolveTypes, except that it
59// recurses down into derived types, merging the used types if the parent types
60// are compatible.
61//
Chris Lattnere3092c92003-08-23 21:25:54 +000062static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
63 const PATypeHolder &SrcTy,
64 SymbolTable *DestST, const std::string &Name,
65 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000066 const Type *SrcTyT = SrcTy.get();
67 const Type *DestTyT = DestTy.get();
68 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +000069
70 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000071 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
72 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +000073
74 // Two types cannot be resolved together if they are of different primitive
75 // type. For example, we cannot resolve an int to a float.
Chris Lattner43f4ba82003-08-22 19:12:55 +000076 if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +000077
78 // Otherwise, resolve the used type used by this derived type...
Chris Lattner43f4ba82003-08-22 19:12:55 +000079 switch (DestTyT->getPrimitiveID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000080 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +000081 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +000082 cast<FunctionType>(SrcTyT)->isVarArg() ||
83 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
84 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +000085 return true;
86 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +000087 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
88 getFT(SrcTy)->getContainedType(i), DestST, "",
89 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +000090 return true;
91 return false;
92 }
93 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +000094 if (getST(DestTy)->getNumContainedTypes() !=
95 getST(SrcTy)->getNumContainedTypes()) return 1;
96 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +000097 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
98 getST(SrcTy)->getContainedType(i), DestST, "",
99 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000100 return true;
101 return false;
102 }
103 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000104 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
105 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000106 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000107 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
108 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000109 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000110 case Type::PointerTyID: {
111 // If this is a pointer type, check to see if we have already seen it. If
112 // so, we are in a recursive branch. Cut off the search now. We cannot use
113 // an associative container for this search, because the type pointers (keys
114 // in the container) change whenever types get resolved...
115 //
116 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
117 if (Pointers[i].first == DestTy)
118 return Pointers[i].second != SrcTy;
119
120 // Otherwise, add the current pointers to the vector to stop recursion on
121 // this pair.
122 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
123 bool Result =
124 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
125 cast<PointerType>(SrcTy.get())->getElementType(),
126 DestST, "", Pointers);
127 Pointers.pop_back();
128 return Result;
129 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000130 default: assert(0 && "Unexpected type!"); return true;
131 }
132}
133
Chris Lattnere3092c92003-08-23 21:25:54 +0000134static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
135 const PATypeHolder &SrcTy,
136 SymbolTable *DestST, const std::string &Name){
137 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
138 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
139}
140
Chris Lattnere76c57a2003-08-22 06:07:12 +0000141
Chris Lattner2c236f32001-11-03 05:18:24 +0000142// LinkTypes - Go through the symbol table of the Src module and see if any
143// types are named in the src module that are not named in the Dst module.
144// Make sure there are no type name conflicts.
145//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000146static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000147 SymbolTable *DestST = &Dest->getSymbolTable();
148 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000149
150 // Look for a type plane for Type's...
151 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
152 if (PI == SrcST->end()) return false; // No named types, do nothing.
153
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000154 // Some types cannot be resolved immediately because they depend on other
155 // types being resolved to each other first. This contains a list of types we
156 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000157 std::vector<std::string> DelayedTypesToResolve;
158
Chris Lattner2c236f32001-11-03 05:18:24 +0000159 const SymbolTable::VarMap &VM = PI->second;
160 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
161 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000162 const std::string &Name = I->first;
Chris Lattner4c00e532003-05-15 16:30:55 +0000163 Type *RHS = cast<Type>(I->second);
Chris Lattner2c236f32001-11-03 05:18:24 +0000164
165 // Check to see if this type name is already in the dest module...
Chris Lattner4c00e532003-05-15 16:30:55 +0000166 Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000167
Chris Lattner4c00e532003-05-15 16:30:55 +0000168 if (ResolveTypes(Entry, RHS, DestST, Name)) {
169 // They look different, save the types 'till later to resolve.
170 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000171 }
172 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000173
174 // Iteratively resolve types while we can...
175 while (!DelayedTypesToResolve.empty()) {
176 // Loop over all of the types, attempting to resolve them if possible...
177 unsigned OldSize = DelayedTypesToResolve.size();
178
Chris Lattnere76c57a2003-08-22 06:07:12 +0000179 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000180 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
181 const std::string &Name = DelayedTypesToResolve[i];
182 Type *T1 = cast<Type>(VM.find(Name)->second);
183 Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
184 if (!ResolveTypes(T2, T1, DestST, Name)) {
185 // We are making progress!
186 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
187 --i;
188 }
189 }
190
191 // Did we not eliminate any types?
192 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000193 // Attempt to resolve subelements of types. This allows us to merge these
194 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000195 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
196 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattner43f4ba82003-08-22 19:12:55 +0000197 PATypeHolder T1(cast<Type>(VM.find(Name)->second));
198 PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000199
200 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
201 // We are making progress!
202 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
203
204 // Go back to the main loop, perhaps we can resolve directly by name
205 // now...
206 break;
207 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000208 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000209
210 // If we STILL cannot resolve the types, then there is something wrong.
211 // Report the error.
212 if (DelayedTypesToResolve.size() == OldSize) {
213 // Build up an error message of all of the mismatched types.
214 std::string ErrorMessage;
215 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
216 const std::string &Name = DelayedTypesToResolve[i];
217 const Type *T1 = cast<Type>(VM.find(Name)->second);
218 const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
219 ErrorMessage += " Type named '" + Name +
220 "' conflicts.\n Src='" + T1->getDescription() +
221 "'.\n Dest='" + T2->getDescription() + "'\n";
222 }
223 return Error(Err, "Type conflict between types in modules:\n" +
224 ErrorMessage);
225 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000226 }
227 }
228
229
Chris Lattner2c236f32001-11-03 05:18:24 +0000230 return false;
231}
232
Chris Lattner5c2d3352003-01-30 19:53:34 +0000233static void PrintMap(const std::map<const Value*, Value*> &M) {
234 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000235 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000236 std::cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000237 I->first->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000238 std::cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000239 I->second->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000240 std::cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000241 }
242}
243
244
Chris Lattner5c377c52001-10-14 23:29:15 +0000245// RemapOperand - Use LocalMap and GlobalMap to convert references from one
246// module to another. This is somewhat sophisticated in that it can
247// automatically handle constant references correctly as well...
248//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000249static Value *RemapOperand(const Value *In,
250 std::map<const Value*, Value*> &LocalMap,
251 std::map<const Value*, Value*> *GlobalMap) {
252 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
Chris Lattner5c377c52001-10-14 23:29:15 +0000253 if (I != LocalMap.end()) return I->second;
254
255 if (GlobalMap) {
256 I = GlobalMap->find(In);
257 if (I != GlobalMap->end()) return I->second;
258 }
259
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000260 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattner18961502002-06-25 16:12:52 +0000261 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattner6cdf1972002-07-18 00:13:08 +0000262 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000263 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000264
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000265 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000266
Chris Lattner18961502002-06-25 16:12:52 +0000267 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000268 const std::vector<Use> &Ops = CPA->getValues();
269 std::vector<Constant*> Operands(Ops.size());
Chris Lattnere306d942002-07-18 02:31:03 +0000270 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000271 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000272 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
273 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000274 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000275 const std::vector<Use> &Ops = CPS->getValues();
276 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000277 for (unsigned i = 0; i < Ops.size(); ++i)
278 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000279 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
280 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
281 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000282 Result = const_cast<Constant*>(CPV);
283 } else if (const ConstantPointerRef *CPR =
284 dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000285 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000286 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000287 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000288 if (CE->getOpcode() == Instruction::GetElementPtr) {
289 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
290 std::vector<Constant*> Indices;
291 Indices.reserve(CE->getNumOperands()-1);
292 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
293 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
294 LocalMap, GlobalMap)));
295
296 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
297 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000298 // Cast instruction
299 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000300 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000301 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattner6cdf1972002-07-18 00:13:08 +0000302 } else if (CE->getNumOperands() == 2) {
303 // Binary operator...
304 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
305 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
306
307 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnere8e46052002-07-30 18:54:22 +0000308 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000309 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000310 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000311 }
312
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000313 } else {
314 assert(0 && "Unknown type of derived type constant value!");
315 }
316
317 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000318 if (GlobalMap)
319 GlobalMap->insert(std::make_pair(In, Result));
320 else
321 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000322 return Result;
323 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000324
Chris Lattner5c2d3352003-01-30 19:53:34 +0000325 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000326 PrintMap(LocalMap);
327
328 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000329 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000330 PrintMap(*GlobalMap);
331 }
332
Chris Lattner5c2d3352003-01-30 19:53:34 +0000333 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000334 assert(0 && "Couldn't remap value!");
335 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000336}
337
Chris Lattnerfcd02342003-08-23 20:31:10 +0000338/// FindGlobalNamed - Look in the specified symbol table for a global with the
339/// specified name and type. If an exactly matching global does not exist, see
340/// if there is a global which is "type compatible" with the specified
341/// name/type. This allows us to resolve things like '%x = global int*' with
342/// '%x = global opaque*'.
343///
344static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
345 SymbolTable *ST) {
346 // See if an exact match exists in the symbol table...
347 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
348
349 // It doesn't exist exactly, scan through all of the type planes in the symbol
350 // table, checking each of them for a type-compatible version.
351 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000352 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
Chris Lattner77c5f732003-08-24 19:30:20 +0000353 if (I->first != Type::TypeTy) {
Chris Lattnerf44c6052003-08-23 21:32:24 +0000354 SymbolTable::VarMap &VM = I->second;
355 // Does this type plane contain an entry with the specified name?
356 SymbolTable::type_iterator TI = VM.find(Name);
357 if (TI != VM.end()) {
358 // Determine whether we can fold the two types together, resolving them.
359 // If so, we can use this value.
360 if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
361 return cast<GlobalValue>(TI->second);
362 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000363 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000364 return 0; // Otherwise, nothing could be found.
365}
366
Chris Lattner5c377c52001-10-14 23:29:15 +0000367
368// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000369// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000370//
371static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000372 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000373 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000374 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000375 // We will need a module level symbol table if the src module has a module
376 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000377 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000378
379 // Loop over all of the globals in the src module, mapping them over as we go
380 //
381 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000382 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000383 GlobalVariable *DGV = 0;
384 if (SGV->hasName()) {
385 // A same named thing is a global variable, because the only two things
Chris Lattner79df7c02002-03-26 18:01:55 +0000386 // that may be in a module level symbol table are Global Vars and
387 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000388 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000389 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
390 SGV->getType(), ST));
Chris Lattner4ad02e72003-04-16 20:28:45 +0000391 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000392
Chris Lattner4ad02e72003-04-16 20:28:45 +0000393 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
394 "Global must either be external or have an initializer!");
395
Chris Lattner0fec08e2003-04-21 21:07:05 +0000396 bool SGExtern = SGV->isExternal();
397 bool DGExtern = DGV ? DGV->isExternal() : false;
398
Chris Lattner4ad02e72003-04-16 20:28:45 +0000399 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
400 // No linking to be performed, simply create an identical version of the
401 // symbol over in the dest module... the initializer will be filled in
402 // later by LinkGlobalInits...
403 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000404 GlobalVariable *NewDGV =
405 new GlobalVariable(SGV->getType()->getElementType(),
406 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
407 SGV->getName(), Dest);
408
409 // If the LLVM runtime renamed the global, but it is an externally visible
410 // symbol, DGV must be an existing global with internal linkage. Rename
411 // it.
412 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
413 assert(DGV && DGV->getName() == SGV->getName() &&
414 DGV->hasInternalLinkage());
415 DGV->setName("");
416 NewDGV->setName(SGV->getName()); // Force the name back
417 DGV->setName(SGV->getName()); // This will cause a renaming
418 assert(NewDGV->getName() == SGV->getName() &&
419 DGV->getName() != SGV->getName());
420 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000421
422 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000423 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000424 if (SGV->hasAppendingLinkage())
425 // Keep track that this is an appending variable...
426 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
427
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000428 } else if (SGV->isExternal()) {
429 // If SGV is external or if both SGV & DGV are external.. Just link the
430 // external globals, we aren't adding anything.
431 ValueMap.insert(std::make_pair(SGV, DGV));
432
433 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
434 ValueMap.insert(std::make_pair(SGV, DGV));
435 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
436 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000437 return Error(Err, "Global variables named '" + SGV->getName() +
438 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000439 } else if (SGV->hasExternalLinkage()) {
440 // Allow linking two exactly identical external global variables...
441 if (SGV->isConstant() != DGV->isConstant() ||
442 SGV->getInitializer() != DGV->getInitializer())
443 return Error(Err, "Global Variable Collision on '" +
444 SGV->getType()->getDescription() + " %" + SGV->getName() +
445 "' - Global variables differ in const'ness");
446 ValueMap.insert(std::make_pair(SGV, DGV));
447 } else if (SGV->hasLinkOnceLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000448 // If the global variable has a name, and that name is already in use in
449 // the Dest module, make sure that the name is a compatible global
450 // variable...
451 //
Chris Lattner5c377c52001-10-14 23:29:15 +0000452 // Check to see if the two GV's have the same Const'ness...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000453 if (SGV->isConstant() != DGV->isConstant())
Chris Lattner5c377c52001-10-14 23:29:15 +0000454 return Error(Err, "Global Variable Collision on '" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000455 SGV->getType()->getDescription() + " %" + SGV->getName() +
456 "' - Global variables differ in const'ness");
Chris Lattner0fec08e2003-04-21 21:07:05 +0000457
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000458 // Okay, everything is cool, remember the mapping...
Chris Lattner697954c2002-01-20 22:54:45 +0000459 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000460 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000461 // No linking is performed yet. Just insert a new copy of the global, and
462 // keep track of the fact that it is an appending variable in the
463 // AppendingVars map. The name is cleared out so that no linkage is
464 // performed.
465 GlobalVariable *NewDGV =
466 new GlobalVariable(SGV->getType()->getElementType(),
467 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
468 "", Dest);
469
470 // Make sure to remember this mapping...
471 ValueMap.insert(std::make_pair(SGV, NewDGV));
472
473 // Keep track that this is an appending variable...
474 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000475 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000476 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000477 }
478 }
479 return false;
480}
481
482
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000483// LinkGlobalInits - Update the initializers in the Dest module now that all
484// globals that may be referenced are in Dest.
485//
486static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000487 std::map<const Value*, Value*> &ValueMap,
488 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000489
490 // Loop over all of the globals in the src module, mapping them over as we go
491 //
492 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000493 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000494
495 if (SGV->hasInitializer()) { // Only process initialized GV's
496 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000497 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000498 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000499
500 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000501 if (DGV->hasInitializer()) {
502 assert(SGV->getLinkage() == DGV->getLinkage());
503 if (SGV->hasExternalLinkage()) {
504 if (DGV->getInitializer() != SInit)
505 return Error(Err, "Global Variable Collision on '" +
506 SGV->getType()->getDescription() +"':%"+SGV->getName()+
507 " - Global variables have different initializers");
508 } else if (DGV->hasLinkOnceLinkage()) {
509 // Nothing is required, mapped values will take the new global
510 // automatically.
511 } else if (DGV->hasAppendingLinkage()) {
512 assert(0 && "Appending linkage unimplemented!");
513 } else {
514 assert(0 && "Unknown linkage!");
515 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000516 } else {
517 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000518 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000519 }
520 }
521 }
522 return false;
523}
Chris Lattner5c377c52001-10-14 23:29:15 +0000524
Chris Lattner79df7c02002-03-26 18:01:55 +0000525// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000526// without doing function bodies... this just adds external function prototypes
527// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000528//
Chris Lattner79df7c02002-03-26 18:01:55 +0000529static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000530 std::map<const Value*, Value*> &ValueMap,
531 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000532 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000533
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000534 // Loop over all of the functions in the src module, mapping them over as we
535 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000536 //
537 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000538 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000539 Function *DF = 0;
540 if (SF->hasName())
Chris Lattner79df7c02002-03-26 18:01:55 +0000541 // The same named thing is a Function, because the only two things
542 // that may be in a module level symbol table are Global Vars and
543 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000544 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000545 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
546 ST));
Chris Lattner5c377c52001-10-14 23:29:15 +0000547
Chris Lattner4ad02e72003-04-16 20:28:45 +0000548 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000549 // Function does not already exist, simply insert an function signature
550 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000551 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
552 SF->getName(), Dest);
553
554 // If the LLVM runtime renamed the function, but it is an externally
555 // visible symbol, DF must be an existing function with internal linkage.
556 // Rename it.
557 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
558 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
559 DF->setName("");
560 NewDF->setName(SF->getName()); // Force the name back
561 DF->setName(SF->getName()); // This will cause a renaming
562 assert(NewDF->getName() == SF->getName() &&
563 DF->getName() != SF->getName());
564 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000565
566 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000567 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000568 } else if (SF->isExternal()) {
569 // If SF is external or if both SF & DF are external.. Just link the
570 // external functions, we aren't adding anything.
571 ValueMap.insert(std::make_pair(SF, DF));
572 } else if (DF->isExternal()) { // If DF is external but SF is not...
573 // Link the external functions, update linkage qualifiers
574 ValueMap.insert(std::make_pair(SF, DF));
575 DF->setLinkage(SF->getLinkage());
576
577 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000578 return Error(Err, "Functions named '" + SF->getName() +
579 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000580 } else if (SF->hasExternalLinkage()) {
581 // The function is defined in both modules!!
582 return Error(Err, "Function '" +
583 SF->getFunctionType()->getDescription() + "':\"" +
584 SF->getName() + "\" - Function is already defined!");
585 } else if (SF->hasLinkOnceLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000586 // Completely ignore the source function.
Chris Lattner18961502002-06-25 16:12:52 +0000587 ValueMap.insert(std::make_pair(SF, DF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000588 } else {
589 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000590 }
591 }
592 return false;
593}
594
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000595// LinkFunctionBody - Copy the source function over into the dest function and
596// fix up references to values. At this point we know that Dest is an external
597// function, and that Src is not.
Chris Lattner5c377c52001-10-14 23:29:15 +0000598//
Chris Lattner79df7c02002-03-26 18:01:55 +0000599static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000600 std::map<const Value*, Value*> &GlobalMap,
601 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000602 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000603 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000604
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000605 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000606 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000607 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000608 I != E; ++I, ++DI) {
609 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000610
611 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000612 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000613 }
614
615 // Loop over all of the basic blocks, copying the instructions over...
616 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000617 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000618 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000619 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
620 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000621
622 // Loop over all of the instructions in the src basic block, copying them
623 // over. Note that this is broken in a strict sense because the cloned
624 // instructions will still be referencing values in the Src module, not
625 // the remapped values. In our case, however, we will not get caught and
626 // so we can delay patching the values up until later...
627 //
Chris Lattner18961502002-06-25 16:12:52 +0000628 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000629 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000630 Instruction *DI = II->clone();
631 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000632 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000633 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000634 }
635 }
636
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000637 // At this point, all of the instructions and values of the function are now
638 // copied over. The only problem is that they are still referencing values in
639 // the Source function as operands. Loop through all of the operands of the
640 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000641 //
Chris Lattner18961502002-06-25 16:12:52 +0000642 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
643 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
644 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000645 OI != OE; ++OI)
646 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000647
648 return false;
649}
650
651
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000652// LinkFunctionBodies - Link in the function bodies that are defined in the
653// source module into the DestModule. This consists basically of copying the
654// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000655//
Chris Lattner79df7c02002-03-26 18:01:55 +0000656static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000657 std::map<const Value*, Value*> &ValueMap,
658 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000659
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000660 // Loop over all of the functions in the src module, mapping them over as we
661 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000662 //
Chris Lattner18961502002-06-25 16:12:52 +0000663 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
664 if (!SF->isExternal()) { // No body if function is external
665 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000666
Chris Lattner18961502002-06-25 16:12:52 +0000667 // DF not external SF external?
668 if (!DF->isExternal()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000669 if (DF->hasLinkOnceLinkage()) continue; // No relinkage for link-once!
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000670 if (Err)
Chris Lattner5c2d3352003-01-30 19:53:34 +0000671 *Err = "Function '" + (SF->hasName() ? SF->getName() :std::string(""))
672 + "' body multiply defined!";
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000673 return true;
674 }
675
Chris Lattner18961502002-06-25 16:12:52 +0000676 if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000677 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000678 }
679 return false;
680}
681
Chris Lattner8166e6e2003-05-13 21:33:43 +0000682// LinkAppendingVars - If there were any appending global variables, link them
683// together now. Return true on error.
684//
685static bool LinkAppendingVars(Module *M,
686 std::multimap<std::string, GlobalVariable *> &AppendingVars,
687 std::string *ErrorMsg) {
688 if (AppendingVars.empty()) return false; // Nothing to do.
689
690 // Loop over the multimap of appending vars, processing any variables with the
691 // same name, forming a new appending global variable with both of the
692 // initializers merged together, then rewrite references to the old variables
693 // and delete them.
694 //
695 std::vector<Constant*> Inits;
696 while (AppendingVars.size() > 1) {
697 // Get the first two elements in the map...
698 std::multimap<std::string,
699 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
700
701 // If the first two elements are for different names, there is no pair...
702 // Otherwise there is a pair, so link them together...
703 if (First->first == Second->first) {
704 GlobalVariable *G1 = First->second, *G2 = Second->second;
705 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
706 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
707
708 // Check to see that they two arrays agree on type...
709 if (T1->getElementType() != T2->getElementType())
710 return Error(ErrorMsg,
711 "Appending variables with different element types need to be linked!");
712 if (G1->isConstant() != G2->isConstant())
713 return Error(ErrorMsg,
714 "Appending variables linked with different const'ness!");
715
716 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
717 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
718
719 // Create the new global variable...
720 GlobalVariable *NG =
721 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
722 /*init*/0, First->first, M);
723
724 // Merge the initializer...
725 Inits.reserve(NewSize);
726 ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
727 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
728 Inits.push_back(cast<Constant>(I->getValues()[i]));
729 I = cast<ConstantArray>(G2->getInitializer());
730 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
731 Inits.push_back(cast<Constant>(I->getValues()[i]));
732 NG->setInitializer(ConstantArray::get(NewType, Inits));
733 Inits.clear();
734
735 // Replace any uses of the two global variables with uses of the new
736 // global...
737
738 // FIXME: This should rewrite simple/straight-forward uses such as
739 // getelementptr instructions to not use the Cast!
740 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
741 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
742 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
743
744 // Remove the two globals from the module now...
745 M->getGlobalList().erase(G1);
746 M->getGlobalList().erase(G2);
747
748 // Put the new global into the AppendingVars map so that we can handle
749 // linking of more than two vars...
750 Second->second = NG;
751 }
752 AppendingVars.erase(First);
753 }
754
755 return false;
756}
Chris Lattner52f7e902001-10-13 07:03:50 +0000757
758
759// LinkModules - This function links two modules together, with the resulting
760// left module modified to be the composite of the two input modules. If an
761// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000762// the problem. Upon failure, the Dest module could be in a modified state, and
763// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000764//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000765bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Chris Lattner873c5e72003-08-24 19:26:42 +0000766 if (Dest->getEndianness() == Module::AnyEndianness)
767 Dest->setEndianness(Src->getEndianness());
768 if (Dest->getPointerSize() == Module::AnyPointerSize)
769 Dest->setPointerSize(Src->getPointerSize());
770
771 if (Src->getEndianness() != Module::AnyEndianness &&
772 Dest->getEndianness() != Src->getEndianness())
Chris Lattner43a99942003-04-22 19:13:20 +0000773 std::cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000774 if (Src->getPointerSize() != Module::AnyPointerSize &&
775 Dest->getPointerSize() != Src->getPointerSize())
Chris Lattner43a99942003-04-22 19:13:20 +0000776 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000777
778 // LinkTypes - Go through the symbol table of the Src module and see if any
779 // types are named in the src module that are not named in the Dst module.
780 // Make sure there are no type name conflicts.
781 //
782 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
783
Chris Lattner5c377c52001-10-14 23:29:15 +0000784 // ValueMap - Mapping of values from what they used to be in Src, to what they
785 // are now in Dest.
786 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000787 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000788
Chris Lattner8166e6e2003-05-13 21:33:43 +0000789 // AppendingVars - Keep track of global variables in the destination module
790 // with appending linkage. After the module is linked together, they are
791 // appended and the module is rewritten.
792 //
793 std::multimap<std::string, GlobalVariable *> AppendingVars;
794
795 // Add all of the appending globals already in the Dest module to
796 // AppendingVars.
797 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
Chris Lattnerf4146462003-05-14 12:11:51 +0000798 if (I->hasAppendingLinkage())
799 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000800
801 // Insert all of the globals in src into the Dest module... without linking
802 // initializers (which could refer to functions not yet mapped over).
803 //
804 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000805
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000806 // Link the functions together between the two modules, without doing function
807 // bodies... this just adds external function prototypes to the Dest
808 // function... We do this so that when we begin processing function bodies,
809 // all of the global values that may be referenced are available in our
810 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000811 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000812 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000813
Chris Lattner6cdf1972002-07-18 00:13:08 +0000814 // Update the initializers in the Dest module now that all globals that may
815 // be referenced are in Dest.
816 //
817 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
818
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000819 // Link in the function bodies that are defined in the source module into the
820 // DestModule. This consists basically of copying the function over and
821 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000822 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000823 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000824
Chris Lattner8166e6e2003-05-13 21:33:43 +0000825 // If there were any appending global variables, link them together now.
826 //
827 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
828
Chris Lattner52f7e902001-10-13 07:03:50 +0000829 return false;
830}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000831