Add #includes to enable buiding in Release mode
[oota-llvm.git] / lib / Transforms / Utils / Linker.cpp
1 //===- Linker.cpp - Module Linker Implementation --------------------------===//
2 //
3 // This file implements the LLVM module linker.
4 //
5 // Specifically, this:
6 //  * Merges global variables between the two modules
7 //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
8 //  * Merges methods between two modules
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Transforms/Linker.h"
13 #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"
19 #include "llvm/ConstPoolVals.h"
20
21 // Error - Simple wrapper function to conditionally assign to E and return true.
22 // This just makes error return conditions a little bit simpler...
23 //
24 static inline bool Error(string *E, string Message) {
25   if (E) *E = Message;
26   return true;
27 }
28
29 #include "llvm/Assembly/Writer.h" // TODO: REMOVE
30
31
32 // LinkTypes - Go through the symbol table of the Src module and see if any
33 // types are named in the src module that are not named in the Dst module.
34 // Make sure there are no type name conflicts.
35 //
36 static bool LinkTypes(Module *Dest, const Module *Src, string *Err = 0) {
37   // No symbol table?  Can't have named types.
38   if (!Src->hasSymbolTable()) return false;
39
40   SymbolTable       *DestST = Dest->getSymbolTableSure();
41   const SymbolTable *SrcST  = Src->getSymbolTable();
42
43   // Look for a type plane for Type's...
44   SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
45   if (PI == SrcST->end()) return false;  // No named types, do nothing.
46
47   const SymbolTable::VarMap &VM = PI->second;
48   for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
49        I != E; ++I) {
50     const string &Name = I->first;
51     const Type *RHS = cast<Type>(I->second);
52
53     // Check to see if this type name is already in the dest module...
54     const Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
55     if (Entry) {     // Yup, the value already exists...
56       if (Entry != RHS)            // If it's the same, noop.  Otherwise, error.
57         return Error(Err, "Type named '" + Name + 
58                      "' of different shape in modules.\n  Src='" + 
59                      Entry->getDescription() + "'.  Dest='" + 
60                      RHS->getDescription() + "'");
61     } else {                       // Type not in dest module.  Add it now.
62       // TODO: FIXME WHEN TYPES AREN'T CONST
63       DestST->insert(Name, const_cast<Type*>(RHS));
64     }
65   }
66   return false;
67 }
68
69 static void PrintMap(const map<const Value*, Value*> &M) {
70   for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
71        I != E; ++I) {
72     cerr << " Fr: " << (void*)I->first << " " << I->first 
73          << " To: " << (void*)I->second << " " << I->second << endl;
74   }
75 }
76
77
78 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
79 // module to another.  This is somewhat sophisticated in that it can
80 // automatically handle constant references correctly as well...
81 //
82 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
83                            const map<const Value*, Value*> *GlobalMap = 0) {
84   map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
85   if (I != LocalMap.end()) return I->second;
86
87   if (GlobalMap) {
88     I = GlobalMap->find(In);
89     if (I != GlobalMap->end()) return I->second;
90   }
91
92   // Check to see if it's a constant that we are interesting in transforming...
93   if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(In)) {
94     if (!isa<DerivedType>(CPV->getType()))
95       return CPV;              // Simple constants stay identical...
96
97     ConstPoolVal *Result = 0;
98
99     if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CPV)) {
100       const vector<Use> &Ops = CPA->getValues();
101       vector<ConstPoolVal*> Operands(Ops.size());
102       for (unsigned i = 0; i < Ops.size(); ++i)
103         Operands[i] = 
104           cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
105       Result = ConstPoolArray::get(cast<ArrayType>(CPA->getType()), Operands);
106     } else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CPV)) {
107       const vector<Use> &Ops = CPS->getValues();
108       vector<ConstPoolVal*> Operands(Ops.size());
109       for (unsigned i = 0; i < Ops.size(); ++i)
110         Operands[i] = 
111           cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
112       Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
113     } else if (isa<ConstPoolPointerNull>(CPV)) {
114       Result = CPV;
115     } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(CPV)) {
116       Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
117       Result = ConstPoolPointerRef::get(cast<GlobalValue>(V));
118     } else {
119       assert(0 && "Unknown type of derived type constant value!");
120     }
121
122     // Cache the mapping in our local map structure...
123     LocalMap.insert(make_pair(In, CPV));
124     return Result;
125   }
126
127   cerr << "XXX LocalMap: \n";
128   PrintMap(LocalMap);
129
130   if (GlobalMap) {
131     cerr << "XXX GlobalMap: \n";
132     PrintMap(*GlobalMap);
133   }
134
135   cerr << "Couldn't remap value: " << (void*)In << " " << In << endl;
136   assert(0 && "Couldn't remap value!");
137   return 0;
138 }
139
140
141 // LinkGlobals - Loop through the global variables in the src module and merge
142 // them into the dest module...
143 //
144 static bool LinkGlobals(Module *Dest, const Module *Src,
145                         map<const Value*, Value*> &ValueMap, string *Err = 0) {
146   // We will need a module level symbol table if the src module has a module
147   // level symbol table...
148   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
149   
150   // Loop over all of the globals in the src module, mapping them over as we go
151   //
152   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
153     const GlobalVariable *SGV = *I;
154     Value *V;
155
156     // If the global variable has a name, and that name is already in use in the
157     // Dest module, make sure that the name is a compatible global variable...
158     //
159     if (SGV->hasName() && (V = ST->lookup(SGV->getType(), SGV->getName()))) {
160       // The same named thing is a global variable, because the only two things
161       // that may be in a module level symbol table are Global Vars and Methods,
162       // and they both have distinct, nonoverlapping, possible types.
163       // 
164       GlobalVariable *DGV = cast<GlobalVariable>(V);
165
166       // Check to see if the two GV's have the same Const'ness...
167       if (SGV->isConstant() != DGV->isConstant())
168         return Error(Err, "Global Variable Collision on '" + 
169                      SGV->getType()->getDescription() + "':%" + SGV->getName() +
170                      " - Global variables differ in const'ness");
171
172       // Okay, everything is cool, remember the mapping...
173       ValueMap.insert(make_pair(SGV, DGV));
174     } else {
175       // No linking to be performed, simply create an identical version of the
176       // symbol over in the dest module... the initializer will be filled in
177       // later by LinkGlobalInits...
178       //
179       GlobalVariable *DGV = 
180         new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
181                            0, SGV->getName());
182
183       // Add the new global to the dest module
184       Dest->getGlobalList().push_back(DGV);
185
186       // Make sure to remember this mapping...
187       ValueMap.insert(make_pair(SGV, DGV));
188     }
189   }
190   return false;
191 }
192
193
194 // LinkGlobalInits - Update the initializers in the Dest module now that all
195 // globals that may be referenced are in Dest.
196 //
197 static bool LinkGlobalInits(Module *Dest, const Module *Src,
198                             map<const Value*, Value*> &ValueMap,
199                             string *Err = 0) {
200
201   // Loop over all of the globals in the src module, mapping them over as we go
202   //
203   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
204     const GlobalVariable *SGV = *I;
205
206     if (SGV->hasInitializer()) {      // Only process initialized GV's
207       // Figure out what the initializer looks like in the dest module...
208       ConstPoolVal *DInit =
209         cast<ConstPoolVal>(RemapOperand(SGV->getInitializer(), ValueMap));
210
211       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
212       if (DGV->hasInitializer()) {
213         if (DGV->getInitializer() != DInit)
214           return Error(Err, "Global Variable Collision on '" + 
215                        SGV->getType()->getDescription() + "':%" +SGV->getName()+
216                        " - Global variables have different initializers");
217       } else {
218         // Copy the initializer over now...
219         DGV->setInitializer(DInit);
220       }
221     }
222   }
223   return false;
224 }
225
226 // LinkMethodProtos - Link the methods together between the two modules, without
227 // doing method bodies... this just adds external method prototypes to the Dest
228 // method...
229 //
230 static bool LinkMethodProtos(Module *Dest, const Module *Src,
231                              map<const Value*, Value*> &ValueMap,
232                              string *Err = 0) {
233   // We will need a module level symbol table if the src module has a module
234   // level symbol table...
235   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
236   
237   // Loop over all of the methods in the src module, mapping them over as we go
238   //
239   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
240     const Method *SM = *I;   // SrcMethod
241     Value *V;
242
243     // If the method has a name, and that name is already in use in the
244     // Dest module, make sure that the name is a compatible method...
245     //
246     if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
247       // The same named thing is a Method, because the only two things
248       // that may be in a module level symbol table are Global Vars and Methods,
249       // and they both have distinct, nonoverlapping, possible types.
250       // 
251       Method *DM = cast<Method>(V);   // DestMethod
252
253       // Check to make sure the method is not defined in both modules...
254       if (!SM->isExternal() && !DM->isExternal())
255         return Error(Err, "Method '" + 
256                      SM->getMethodType()->getDescription() + "':\"" + 
257                      SM->getName() + "\" - Method is already defined!");
258
259       // Otherwise, just remember this mapping...
260       ValueMap.insert(make_pair(SM, DM));
261     } else {
262       // Method does not already exist, simply insert an external method
263       // signature identical to SM into the dest module...
264       Method *DM = new Method(SM->getMethodType(), SM->getName());
265
266       // Add the method signature to the dest module...
267       Dest->getMethodList().push_back(DM);
268
269       // ... and remember this mapping...
270       ValueMap.insert(make_pair(SM, DM));
271     }
272   }
273   return false;
274 }
275
276 // LinkMethodBody - Copy the source method over into the dest method and fix up
277 // references to values.  At this point we know that Dest is an external method,
278 // and that Src is not.
279 //
280 static bool LinkMethodBody(Method *Dest, const Method *Src,
281                            const map<const Value*, Value*> &GlobalMap,
282                            string *Err = 0) {
283   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
284   map<const Value*, Value*> LocalMap;   // Map for method local values
285
286   // Go through and convert method arguments over...
287   for (Method::ArgumentListType::const_iterator 
288          I = Src->getArgumentList().begin(),
289          E = Src->getArgumentList().end(); I != E; ++I) {
290     const MethodArgument *SMA = *I;
291
292     // Create the new method argument and add to the dest method...
293     MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
294     Dest->getArgumentList().push_back(DMA);
295
296     // Add a mapping to our local map
297     LocalMap.insert(make_pair(SMA, DMA));
298   }
299
300   // Loop over all of the basic blocks, copying the instructions over...
301   //
302   for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
303     const BasicBlock *SBB = *I;
304
305     // Create new basic block and add to mapping and the Dest method...
306     BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
307     LocalMap.insert(make_pair(SBB, DBB));
308
309     // Loop over all of the instructions in the src basic block, copying them
310     // over.  Note that this is broken in a strict sense because the cloned
311     // instructions will still be referencing values in the Src module, not
312     // the remapped values.  In our case, however, we will not get caught and 
313     // so we can delay patching the values up until later...
314     //
315     for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end(); 
316          II != IE; ++II) {
317       const Instruction *SI = *II;
318       Instruction *DI = SI->clone();
319       DI->setName(SI->getName());
320       DBB->getInstList().push_back(DI);
321       LocalMap.insert(make_pair(SI, DI));
322     }
323   }
324
325   // At this point, all of the instructions and values of the method are now
326   // copied over.  The only problem is that they are still referencing values
327   // in the Source method as operands.  Loop through all of the operands of the
328   // methods and patch them up to point to the local versions...
329   //
330   for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
331        I != E; ++I) {
332     Instruction *Inst = *I;
333
334     for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
335          OI != OE; ++OI)
336       *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
337   }
338
339   return false;
340 }
341
342
343 // LinkMethodBodies - Link in the method bodies that are defined in the source
344 // module into the DestModule.  This consists basically of copying the method
345 // over and fixing up references to values.
346 //
347 static bool LinkMethodBodies(Module *Dest, const Module *Src,
348                              map<const Value*, Value*> &ValueMap,
349                              string *Err = 0) {
350
351   // Loop over all of the methods in the src module, mapping them over as we go
352   //
353   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
354     const Method *SM = *I;                     // Source Method
355     if (!SM->isExternal()) {                   // No body if method is external
356       Method *DM = cast<Method>(ValueMap[SM]); // Destination method
357
358       // DM not external SM external?
359       if (!DM->isExternal()) {
360         if (Err)
361           *Err = "Method '" + (SM->hasName() ? SM->getName() : string("")) +
362                  "' body multiply defined!";
363         return true;
364       }
365
366       if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
367     }
368   }
369   return false;
370 }
371
372
373
374 // LinkModules - This function links two modules together, with the resulting
375 // left module modified to be the composite of the two input modules.  If an
376 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
377 // the problem.  Upon failure, the Dest module could be in a modified state, and
378 // shouldn't be relied on to be consistent.
379 //
380 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
381
382   // LinkTypes - Go through the symbol table of the Src module and see if any
383   // types are named in the src module that are not named in the Dst module.
384   // Make sure there are no type name conflicts.
385   //
386   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
387
388   // ValueMap - Mapping of values from what they used to be in Src, to what they
389   // are now in Dest.
390   //
391   map<const Value*, Value*> ValueMap;
392
393   // Insert all of the globals in src into the Dest module... without
394   // initializers
395   if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
396
397   // Update the initializers in the Dest module now that all globals that may
398   // be referenced are in Dest.
399   //
400   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
401
402   // Link the methods together between the two modules, without doing method
403   // bodies... this just adds external method prototypes to the Dest method...
404   // We do this so that when we begin processing method bodies, all of the
405   // global values that may be referenced are available in our ValueMap.
406   //
407   if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
408
409   // Link in the method bodies that are defined in the source module into the
410   // DestModule.  This consists basically of copying the method over and fixing
411   // up references to values.
412   //
413   if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
414
415   return false;
416 }
417