Implement linker. It's 95% working now.
[oota-llvm.git] / lib / VMCore / 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 //
9 //===----------------------------------------------------------------------===//
10
11 #include "llvm/Transforms/Linker.h"
12 #include "llvm/Module.h"
13 #include "llvm/Method.h"
14 #include "llvm/GlobalVariable.h"
15 #include "llvm/SymbolTable.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/iOther.h"
18
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 //
22 static inline bool Error(string *E, string Message) {
23   if (E) *E = Message;
24   return true;
25 }
26
27 #include "llvm/Assembly/Writer.h" // TODO: REMOVE
28
29 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
30 // module to another.  This is somewhat sophisticated in that it can
31 // automatically handle constant references correctly as well...
32 //
33 static Value *RemapOperand(Value *In, map<const Value*, Value*> &LocalMap,
34                            const map<const Value*, Value*> *GlobalMap = 0) {
35   map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
36   if (I != LocalMap.end()) return I->second;
37
38   if (GlobalMap) {
39     I = GlobalMap->find(In);
40     if (I != GlobalMap->end()) return I->second;
41   }
42
43   if (!isa<ConstPoolVal>(In))
44     cerr << "Couldn't remap value: " << In << endl;
45   return In;
46 }
47
48
49 // LinkGlobals - Loop through the global variables in the src module and merge
50 // them into the dest module...
51 //
52 static bool LinkGlobals(Module *Dest, const Module *Src,
53                         map<const Value*, Value*> &ValueMap, string *Err = 0) {
54   // We will need a module level symbol table if the src module has a module
55   // level symbol table...
56   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
57   
58   // Loop over all of the globals in the src module, mapping them over as we go
59   //
60   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
61     const GlobalVariable *GV = *I;
62     Value *V;
63
64     // If the global variable has a name, and that name is already in use in the
65     // Dest module, make sure that the name is a compatible global variable...
66     //
67     if (GV->hasName() && (V = ST->lookup(GV->getType(), GV->getName()))) {
68       // The same named thing is a global variable, because the only two things
69       // that may be in a module level symbol table are Global Vars and Methods,
70       // and they both have distinct, nonoverlapping, possible types.
71       // 
72       GlobalVariable *DGV = cast<GlobalVariable>(V);
73
74       // Check to see if the two GV's have the same Const'ness...
75       if (GV->isConstant() != DGV->isConstant())
76         return Error(Err, "Global Variable Collision on '" + 
77                      GV->getType()->getDescription() + "':%" + GV->getName() +
78                      " - Global variables differ in const'ness");
79
80       // Check to make sure that they both have the same initializer if they are
81       // both initialized...
82       //
83  // TODO: Check to see if they have DEEP equality.  For Module level constants
84       if (GV->hasInitializer() && DGV->hasInitializer() &&
85           GV->getInitializer() != DGV->getInitializer())
86         return Error(Err, "Global Variable Collision on '" + 
87                      GV->getType()->getDescription() + "':%" + GV->getName() +
88                      " - Global variables have different initializers");
89
90       // Okay, everything is cool, remember the mapping and update the
91       // initializer if neccesary...
92       //
93 // TODO: We might have to map module level constants here!
94       if (GV->hasInitializer() && !DGV->hasInitializer())
95         DGV->setInitializer(GV->getInitializer());
96
97       ValueMap.insert(make_pair(GV, DGV));
98     } else {
99       // No linking to be performed, simply create an identical version of the
100       // symbol over in the dest module...
101 // TODO: Provide constpoolval mapping for initializer if using module local
102 // initializers!
103       GlobalVariable *NGV = 
104         new GlobalVariable(GV->getType()->getValueType(), GV->isConstant(),
105                            GV->hasInitializer() ? GV->getInitializer() : 0,
106                            GV->getName());
107
108       // Add the new global to the dest module
109       Dest->getGlobalList().push_back(NGV);
110
111       // Make sure to remember this mapping...
112       ValueMap.insert(make_pair(GV, NGV));
113     }
114   }
115   return false;
116 }
117
118
119
120 // LinkMethodProtos - Link the methods together between the two modules, without
121 // doing method bodies... this just adds external method prototypes to the Dest
122 // method...
123 //
124 static bool LinkMethodProtos(Module *Dest, const Module *Src,
125                              map<const Value*, Value*> &ValueMap,
126                              string *Err = 0) {
127   // We will need a module level symbol table if the src module has a module
128   // level symbol table...
129   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
130   
131   // Loop over all of the methods in the src module, mapping them over as we go
132   //
133   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
134     const Method *SM = *I;   // SrcMethod
135     Value *V;
136
137     // If the method has a name, and that name is already in use in the
138     // Dest module, make sure that the name is a compatible method...
139     //
140     if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
141       // The same named thing is a Method, because the only two things
142       // that may be in a module level symbol table are Global Vars and Methods,
143       // and they both have distinct, nonoverlapping, possible types.
144       // 
145       Method *DM = cast<Method>(V);   // DestMethod
146
147       // Check to make sure the method is not defined in both modules...
148       if (!SM->isExternal() && !DM->isExternal())
149         return Error(Err, "Method '" + 
150                      SM->getMethodType()->getDescription() + "':\"" + 
151                      SM->getName() + "\" - Method is already defined!");
152
153       // Otherwise, just remember this mapping...
154       ValueMap.insert(make_pair(SM, DM));
155     } else {
156       // Method does not already exist, simply insert an external method
157       // signature identical to SM into the dest module...
158       Method *DM = new Method(SM->getMethodType(), SM->getName());
159
160       // Add the method signature to the dest module...
161       Dest->getMethodList().push_back(DM);
162
163       // ... and remember this mapping...
164       ValueMap.insert(make_pair(SM, DM));
165     }
166   }
167   return false;
168 }
169
170 // LinkMethodBody - Copy the source method over into the dest method and fix up
171 // references to values.  At this point we know that Dest is an external method,
172 // and that Src is not.
173 //
174 static bool LinkMethodBody(Method *Dest, const Method *Src,
175                            const map<const Value*, Value*> &GlobalMap,
176                            string *Err = 0) {
177   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
178   map<const Value*, Value*> LocalMap;   // Map for method local values
179
180   // Go through and convert method arguments over...
181   for (Method::ArgumentListType::const_iterator 
182          I = Src->getArgumentList().begin(),
183          E = Src->getArgumentList().end(); I != E; ++I) {
184     const MethodArgument *SMA = *I;
185
186     // Create the new method argument and add to the dest method...
187     MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
188     Dest->getArgumentList().push_back(DMA);
189
190     // Add a mapping to our local map
191     LocalMap.insert(make_pair(SMA, DMA));
192   }
193
194   // Loop over all of the basic blocks, copying the instructions over...
195   //
196   for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
197     const BasicBlock *SBB = *I;
198
199     // Create new basic block and add to mapping and the Dest method...
200     BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
201     LocalMap.insert(make_pair(SBB, DBB));
202
203     // Loop over all of the instructions in the src basic block, copying them
204     // over.  Note that this is broken in a strict sense because the cloned
205     // instructions will still be referencing values in the Src module, not
206     // the remapped values.  In our case, however, we will not get caught and 
207     // so we can delay patching the values up until later...
208     //
209     for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end(); 
210          II != IE; ++II) {
211       const Instruction *SI = *II;
212       Instruction *DI = SI->clone();
213       DBB->getInstList().push_back(DI);
214       LocalMap.insert(make_pair(SI, DI));
215     }
216   }
217
218   // At this point, all of the instructions and values of the method are now
219   // copied over.  The only problem is that they are still referencing values
220   // in the Source method as operands.  Loop through all of the operands of the
221   // methods and patch them up to point to the local versions...
222   //
223   for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
224        I != E; ++I) {
225     Instruction *Inst = *I;
226
227     for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
228          OI != OE; ++OI)
229       *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
230   }
231
232   return false;
233 }
234
235
236 // LinkMethodBodies - Link in the method bodies that are defined in the source
237 // module into the DestModule.  This consists basically of copying the method
238 // over and fixing up references to values.
239 //
240 static bool LinkMethodBodies(Module *Dest, const Module *Src,
241                              map<const Value*, Value*> &ValueMap,
242                              string *Err = 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;                   // Source Method
248     Method *DM = cast<Method>(ValueMap[SM]); // Destination method
249
250     assert(DM && DM->isExternal() && "LinkMethodProtos failed!");
251     if (!SM->isExternal())  // External methods are already done
252       if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
253   }
254   return false;
255 }
256
257
258
259 // LinkModules - This function links two modules together, with the resulting
260 // left module modified to be the composite of the two input modules.  If an
261 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
262 // the problem.  Upon failure, the Dest module could be in a modified state, and
263 // shouldn't be relied on to be consistent.
264 //
265 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
266   // ValueMap - Mapping of values from what they used to be in Src, to what they
267   // are now in Dest.
268   //
269   map<const Value*, Value*> ValueMap;
270
271   // Link the globals variables together between the two modules...
272   if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
273
274   // Link the methods together between the two modules, without doing method
275   // bodies... this just adds external method prototypes to the Dest method...
276   // We do this so that when we begin processing method bodies, all of the
277   // global values that may be referenced are available in our ValueMap.
278   //
279   if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
280
281   // Link in the method bodies that are defined in the source module into the
282   // DestModule.  This consists basically of copying the method over and fixing
283   // up references to values.
284   //
285   if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
286
287   return false;
288 }