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