blob: e1622529c26041ffe7e5dc56fdffed3c3291eb8e [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 !=
8// * Merges methods between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10//===----------------------------------------------------------------------===//
11
12#include "llvm/Transforms/Linker.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000013#include "llvm/Module.h"
14#include "llvm/Method.h"
15#include "llvm/GlobalVariable.h"
16#include "llvm/SymbolTable.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/iOther.h"
Chris Lattnere9bb2df2001-12-03 22:26:30 +000019#include "llvm/ConstantVals.h"
Chris Lattner697954c2002-01-20 22:54:45 +000020#include <iostream>
21using std::cerr;
22using std::string;
23using std::map;
Chris Lattner5c377c52001-10-14 23:29:15 +000024
25// Error - Simple wrapper function to conditionally assign to E and return true.
26// This just makes error return conditions a little bit simpler...
27//
28static inline bool Error(string *E, string Message) {
29 if (E) *E = Message;
30 return true;
31}
32
33#include "llvm/Assembly/Writer.h" // TODO: REMOVE
34
Chris Lattner2c236f32001-11-03 05:18:24 +000035
36// LinkTypes - Go through the symbol table of the Src module and see if any
37// types are named in the src module that are not named in the Dst module.
38// Make sure there are no type name conflicts.
39//
40static bool LinkTypes(Module *Dest, const Module *Src, string *Err = 0) {
41 // No symbol table? Can't have named types.
42 if (!Src->hasSymbolTable()) return false;
43
44 SymbolTable *DestST = Dest->getSymbolTableSure();
45 const SymbolTable *SrcST = Src->getSymbolTable();
46
47 // Look for a type plane for Type's...
48 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
49 if (PI == SrcST->end()) return false; // No named types, do nothing.
50
51 const SymbolTable::VarMap &VM = PI->second;
52 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
53 I != E; ++I) {
54 const string &Name = I->first;
55 const Type *RHS = cast<Type>(I->second);
56
57 // Check to see if this type name is already in the dest module...
58 const Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
59 if (Entry) { // Yup, the value already exists...
60 if (Entry != RHS) // If it's the same, noop. Otherwise, error.
61 return Error(Err, "Type named '" + Name +
62 "' of different shape in modules.\n Src='" +
63 Entry->getDescription() + "'. Dest='" +
64 RHS->getDescription() + "'");
65 } else { // Type not in dest module. Add it now.
66 // TODO: FIXME WHEN TYPES AREN'T CONST
67 DestST->insert(Name, const_cast<Type*>(RHS));
68 }
69 }
70 return false;
71}
72
Chris Lattner2d3e8bb2001-11-03 03:27:29 +000073static void PrintMap(const map<const Value*, Value*> &M) {
74 for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
75 I != E; ++I) {
76 cerr << " Fr: " << (void*)I->first << " " << I->first
Chris Lattner697954c2002-01-20 22:54:45 +000077 << " To: " << (void*)I->second << " " << I->second << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +000078 }
79}
80
81
Chris Lattner5c377c52001-10-14 23:29:15 +000082// RemapOperand - Use LocalMap and GlobalMap to convert references from one
83// module to another. This is somewhat sophisticated in that it can
84// automatically handle constant references correctly as well...
85//
Chris Lattner8d2de8a2001-10-15 03:12:52 +000086static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
Chris Lattner5c377c52001-10-14 23:29:15 +000087 const map<const Value*, Value*> *GlobalMap = 0) {
88 map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
89 if (I != LocalMap.end()) return I->second;
90
91 if (GlobalMap) {
92 I = GlobalMap->find(In);
93 if (I != GlobalMap->end()) return I->second;
94 }
95
Chris Lattner8d2de8a2001-10-15 03:12:52 +000096 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattnere9bb2df2001-12-03 22:26:30 +000097 if (Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +000098 if (!isa<DerivedType>(CPV->getType()))
99 return CPV; // Simple constants stay identical...
100
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000101 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000102
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000103 if (ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000104 const std::vector<Use> &Ops = CPA->getValues();
105 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000106 for (unsigned i = 0; i < Ops.size(); ++i)
107 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000108 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
109 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
110 } else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000111 const std::vector<Use> &Ops = CPS->getValues();
112 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000113 for (unsigned i = 0; i < Ops.size(); ++i)
114 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000115 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
116 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
117 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000118 Result = CPV;
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000119 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000120 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000121 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000122 } else {
123 assert(0 && "Unknown type of derived type constant value!");
124 }
125
126 // Cache the mapping in our local map structure...
Chris Lattner697954c2002-01-20 22:54:45 +0000127 LocalMap.insert(std::make_pair(In, CPV));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000128 return Result;
129 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000130
131 cerr << "XXX LocalMap: \n";
132 PrintMap(LocalMap);
133
134 if (GlobalMap) {
135 cerr << "XXX GlobalMap: \n";
136 PrintMap(*GlobalMap);
137 }
138
Chris Lattner697954c2002-01-20 22:54:45 +0000139 cerr << "Couldn't remap value: " << (void*)In << " " << In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000140 assert(0 && "Couldn't remap value!");
141 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000142}
143
144
145// LinkGlobals - Loop through the global variables in the src module and merge
146// them into the dest module...
147//
148static bool LinkGlobals(Module *Dest, const Module *Src,
149 map<const Value*, Value*> &ValueMap, string *Err = 0) {
150 // We will need a module level symbol table if the src module has a module
151 // level symbol table...
152 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
153
154 // Loop over all of the globals in the src module, mapping them over as we go
155 //
156 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000157 const GlobalVariable *SGV = *I;
Chris Lattner5c377c52001-10-14 23:29:15 +0000158 Value *V;
159
160 // If the global variable has a name, and that name is already in use in the
161 // Dest module, make sure that the name is a compatible global variable...
162 //
Chris Lattnere4d25aa2001-11-26 18:59:18 +0000163 if (SGV->hasExternalLinkage() && SGV->hasName() &&
164 (V = ST->lookup(SGV->getType(), SGV->getName())) &&
165 cast<GlobalVariable>(V)->hasExternalLinkage()) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000166 // The same named thing is a global variable, because the only two things
167 // that may be in a module level symbol table are Global Vars and Methods,
168 // and they both have distinct, nonoverlapping, possible types.
169 //
170 GlobalVariable *DGV = cast<GlobalVariable>(V);
171
172 // Check to see if the two GV's have the same Const'ness...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000173 if (SGV->isConstant() != DGV->isConstant())
Chris Lattner5c377c52001-10-14 23:29:15 +0000174 return Error(Err, "Global Variable Collision on '" +
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000175 SGV->getType()->getDescription() + "':%" + SGV->getName() +
Chris Lattner5c377c52001-10-14 23:29:15 +0000176 " - Global variables differ in const'ness");
177
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000178 // Okay, everything is cool, remember the mapping...
Chris Lattner697954c2002-01-20 22:54:45 +0000179 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000180 } else {
181 // No linking to be performed, simply create an identical version of the
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000182 // symbol over in the dest module... the initializer will be filled in
183 // later by LinkGlobalInits...
184 //
185 GlobalVariable *DGV =
Chris Lattner7a176752001-12-04 00:03:30 +0000186 new GlobalVariable(SGV->getType()->getElementType(), SGV->isConstant(),
Chris Lattnere4d25aa2001-11-26 18:59:18 +0000187 SGV->hasInternalLinkage(), 0, SGV->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000188
189 // Add the new global to the dest module
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000190 Dest->getGlobalList().push_back(DGV);
Chris Lattner5c377c52001-10-14 23:29:15 +0000191
192 // Make sure to remember this mapping...
Chris Lattner697954c2002-01-20 22:54:45 +0000193 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000194 }
195 }
196 return false;
197}
198
199
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000200// LinkGlobalInits - Update the initializers in the Dest module now that all
201// globals that may be referenced are in Dest.
202//
203static bool LinkGlobalInits(Module *Dest, const Module *Src,
204 map<const Value*, Value*> &ValueMap,
205 string *Err = 0) {
206
207 // Loop over all of the globals in the src module, mapping them over as we go
208 //
209 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
210 const GlobalVariable *SGV = *I;
211
212 if (SGV->hasInitializer()) { // Only process initialized GV's
213 // Figure out what the initializer looks like in the dest module...
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000214 Constant *DInit =
215 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000216
217 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattnere4d25aa2001-11-26 18:59:18 +0000218 if (DGV->hasInitializer() && SGV->hasExternalLinkage() &&
219 DGV->hasExternalLinkage()) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000220 if (DGV->getInitializer() != DInit)
221 return Error(Err, "Global Variable Collision on '" +
222 SGV->getType()->getDescription() + "':%" +SGV->getName()+
223 " - Global variables have different initializers");
224 } else {
225 // Copy the initializer over now...
226 DGV->setInitializer(DInit);
227 }
228 }
229 }
230 return false;
231}
Chris Lattner5c377c52001-10-14 23:29:15 +0000232
233// LinkMethodProtos - Link the methods together between the two modules, without
234// doing method bodies... this just adds external method prototypes to the Dest
235// method...
236//
237static bool LinkMethodProtos(Module *Dest, const Module *Src,
238 map<const Value*, Value*> &ValueMap,
239 string *Err = 0) {
240 // We will need a module level symbol table if the src module has a module
241 // level symbol table...
242 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
243
244 // Loop over all of the methods in the src module, mapping them over as we go
245 //
246 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
247 const Method *SM = *I; // SrcMethod
248 Value *V;
249
250 // If the method has a name, and that name is already in use in the
251 // Dest module, make sure that the name is a compatible method...
252 //
Chris Lattnere4d25aa2001-11-26 18:59:18 +0000253 if (SM->hasExternalLinkage() && SM->hasName() &&
254 (V = ST->lookup(SM->getType(), SM->getName())) &&
255 cast<Method>(V)->hasExternalLinkage()) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000256 // The same named thing is a Method, because the only two things
257 // that may be in a module level symbol table are Global Vars and Methods,
258 // and they both have distinct, nonoverlapping, possible types.
259 //
260 Method *DM = cast<Method>(V); // DestMethod
261
262 // Check to make sure the method is not defined in both modules...
263 if (!SM->isExternal() && !DM->isExternal())
264 return Error(Err, "Method '" +
265 SM->getMethodType()->getDescription() + "':\"" +
266 SM->getName() + "\" - Method is already defined!");
267
268 // Otherwise, just remember this mapping...
Chris Lattner697954c2002-01-20 22:54:45 +0000269 ValueMap.insert(std::make_pair(SM, DM));
Chris Lattner5c377c52001-10-14 23:29:15 +0000270 } else {
271 // Method does not already exist, simply insert an external method
272 // signature identical to SM into the dest module...
Chris Lattnere4d25aa2001-11-26 18:59:18 +0000273 Method *DM = new Method(SM->getMethodType(), SM->hasInternalLinkage(),
274 SM->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000275
276 // Add the method signature to the dest module...
277 Dest->getMethodList().push_back(DM);
278
279 // ... and remember this mapping...
Chris Lattner697954c2002-01-20 22:54:45 +0000280 ValueMap.insert(std::make_pair(SM, DM));
Chris Lattner5c377c52001-10-14 23:29:15 +0000281 }
282 }
283 return false;
284}
285
286// LinkMethodBody - Copy the source method over into the dest method and fix up
287// references to values. At this point we know that Dest is an external method,
288// and that Src is not.
289//
290static bool LinkMethodBody(Method *Dest, const Method *Src,
291 const map<const Value*, Value*> &GlobalMap,
292 string *Err = 0) {
293 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
294 map<const Value*, Value*> LocalMap; // Map for method local values
295
296 // Go through and convert method arguments over...
297 for (Method::ArgumentListType::const_iterator
298 I = Src->getArgumentList().begin(),
299 E = Src->getArgumentList().end(); I != E; ++I) {
300 const MethodArgument *SMA = *I;
301
302 // Create the new method argument and add to the dest method...
303 MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
304 Dest->getArgumentList().push_back(DMA);
305
306 // Add a mapping to our local map
Chris Lattner697954c2002-01-20 22:54:45 +0000307 LocalMap.insert(std::make_pair(SMA, DMA));
Chris Lattner5c377c52001-10-14 23:29:15 +0000308 }
309
310 // Loop over all of the basic blocks, copying the instructions over...
311 //
312 for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
313 const BasicBlock *SBB = *I;
314
315 // Create new basic block and add to mapping and the Dest method...
316 BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
Chris Lattner697954c2002-01-20 22:54:45 +0000317 LocalMap.insert(std::make_pair(SBB, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000318
319 // Loop over all of the instructions in the src basic block, copying them
320 // over. Note that this is broken in a strict sense because the cloned
321 // instructions will still be referencing values in the Src module, not
322 // the remapped values. In our case, however, we will not get caught and
323 // so we can delay patching the values up until later...
324 //
325 for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end();
326 II != IE; ++II) {
327 const Instruction *SI = *II;
328 Instruction *DI = SI->clone();
Chris Lattner43a6f2e2001-10-29 16:55:41 +0000329 DI->setName(SI->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000330 DBB->getInstList().push_back(DI);
Chris Lattner697954c2002-01-20 22:54:45 +0000331 LocalMap.insert(std::make_pair(SI, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000332 }
333 }
334
335 // At this point, all of the instructions and values of the method are now
336 // copied over. The only problem is that they are still referencing values
337 // in the Source method as operands. Loop through all of the operands of the
338 // methods and patch them up to point to the local versions...
339 //
340 for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
341 I != E; ++I) {
342 Instruction *Inst = *I;
343
344 for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
345 OI != OE; ++OI)
346 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
347 }
348
349 return false;
350}
351
352
353// LinkMethodBodies - Link in the method bodies that are defined in the source
354// module into the DestModule. This consists basically of copying the method
355// over and fixing up references to values.
356//
357static bool LinkMethodBodies(Module *Dest, const Module *Src,
358 map<const Value*, Value*> &ValueMap,
359 string *Err = 0) {
360
361 // Loop over all of the methods in the src module, mapping them over as we go
362 //
363 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000364 const Method *SM = *I; // Source Method
365 if (!SM->isExternal()) { // No body if method is external
366 Method *DM = cast<Method>(ValueMap[SM]); // Destination method
Chris Lattner5c377c52001-10-14 23:29:15 +0000367
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000368 // DM not external SM external?
369 if (!DM->isExternal()) {
370 if (Err)
371 *Err = "Method '" + (SM->hasName() ? SM->getName() : string("")) +
372 "' body multiply defined!";
373 return true;
374 }
375
Chris Lattner5c377c52001-10-14 23:29:15 +0000376 if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000377 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000378 }
379 return false;
380}
381
Chris Lattner52f7e902001-10-13 07:03:50 +0000382
383
384// LinkModules - This function links two modules together, with the resulting
385// left module modified to be the composite of the two input modules. If an
386// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000387// the problem. Upon failure, the Dest module could be in a modified state, and
388// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000389//
390bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
Chris Lattner2c236f32001-11-03 05:18:24 +0000391
392 // LinkTypes - Go through the symbol table of the Src module and see if any
393 // types are named in the src module that are not named in the Dst module.
394 // Make sure there are no type name conflicts.
395 //
396 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
397
Chris Lattner5c377c52001-10-14 23:29:15 +0000398 // ValueMap - Mapping of values from what they used to be in Src, to what they
399 // are now in Dest.
400 //
401 map<const Value*, Value*> ValueMap;
402
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000403 // Insert all of the globals in src into the Dest module... without
404 // initializers
Chris Lattner5c377c52001-10-14 23:29:15 +0000405 if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
406
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000407 // Update the initializers in the Dest module now that all globals that may
408 // be referenced are in Dest.
409 //
410 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
411
Chris Lattner5c377c52001-10-14 23:29:15 +0000412 // Link the methods together between the two modules, without doing method
413 // bodies... this just adds external method prototypes to the Dest method...
414 // We do this so that when we begin processing method bodies, all of the
415 // global values that may be referenced are available in our ValueMap.
416 //
417 if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
418
419 // Link in the method bodies that are defined in the source module into the
420 // DestModule. This consists basically of copying the method over and fixing
421 // up references to values.
422 //
423 if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000424
425 return false;
426}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000427