LinkModules.cpp revision c18545dc9e5c8d98ea9089af8702a6cf563a8dfd
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//
23static 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//
34static 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//
88static 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//
141static 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//
174static 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//
224static 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      DBB->getInstList().push_back(DI);
264      LocalMap.insert(make_pair(SI, DI));
265    }
266  }
267
268  // At this point, all of the instructions and values of the method are now
269  // copied over.  The only problem is that they are still referencing values
270  // in the Source method as operands.  Loop through all of the operands of the
271  // methods and patch them up to point to the local versions...
272  //
273  for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
274       I != E; ++I) {
275    Instruction *Inst = *I;
276
277    for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
278         OI != OE; ++OI)
279      *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
280  }
281
282  return false;
283}
284
285
286// LinkMethodBodies - Link in the method bodies that are defined in the source
287// module into the DestModule.  This consists basically of copying the method
288// over and fixing up references to values.
289//
290static bool LinkMethodBodies(Module *Dest, const Module *Src,
291                             map<const Value*, Value*> &ValueMap,
292                             string *Err = 0) {
293
294  // Loop over all of the methods in the src module, mapping them over as we go
295  //
296  for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
297    const Method *SM = *I;                   // Source Method
298    Method *DM = cast<Method>(ValueMap[SM]); // Destination method
299
300    assert(DM && DM->isExternal() && "LinkMethodProtos failed!");
301    if (!SM->isExternal())  // External methods are already done
302      if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
303  }
304  return false;
305}
306
307
308
309// LinkModules - This function links two modules together, with the resulting
310// left module modified to be the composite of the two input modules.  If an
311// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
312// the problem.  Upon failure, the Dest module could be in a modified state, and
313// shouldn't be relied on to be consistent.
314//
315bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
316  // ValueMap - Mapping of values from what they used to be in Src, to what they
317  // are now in Dest.
318  //
319  map<const Value*, Value*> ValueMap;
320
321  // Insert all of the globals in src into the Dest module... without
322  // initializers
323  if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
324
325  // Update the initializers in the Dest module now that all globals that may
326  // be referenced are in Dest.
327  //
328  if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
329
330  // Link the methods together between the two modules, without doing method
331  // bodies... this just adds external method prototypes to the Dest method...
332  // We do this so that when we begin processing method bodies, all of the
333  // global values that may be referenced are available in our ValueMap.
334  //
335  if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
336
337  // Link in the method bodies that are defined in the source module into the
338  // DestModule.  This consists basically of copying the method over and fixing
339  // up references to values.
340  //
341  if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
342
343  return false;
344}
345