1 //===- Linker.cpp - Module Linker Implementation --------------------------===//
3 // This file implements the LLVM module linker.
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
10 //===----------------------------------------------------------------------===//
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"
20 // Error - Simple wrapper function to conditionally assign to E and return true.
21 // This just makes error return conditions a little bit simpler...
23 static inline bool Error(string *E, string Message) {
28 #include "llvm/Assembly/Writer.h" // TODO: REMOVE
30 static void PrintMap(const map<const Value*, Value*> &M) {
31 for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
33 cerr << " Fr: " << (void*)I->first << " " << I->first
34 << " To: " << (void*)I->second << " " << I->second << endl;
39 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
40 // module to another. This is somewhat sophisticated in that it can
41 // automatically handle constant references correctly as well...
43 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
44 const map<const Value*, Value*> *GlobalMap = 0) {
45 map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
46 if (I != LocalMap.end()) return I->second;
49 I = GlobalMap->find(In);
50 if (I != GlobalMap->end()) return I->second;
53 // Check to see if it's a constant that we are interesting in transforming...
54 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(In)) {
55 if (!isa<DerivedType>(CPV->getType()))
56 return CPV; // Simple constants stay identical...
58 ConstPoolVal *Result = 0;
60 if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CPV)) {
61 const vector<Use> &Ops = CPA->getValues();
62 vector<ConstPoolVal*> Operands(Ops.size());
63 for (unsigned i = 0; i < Ops.size(); ++i)
65 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
66 Result = ConstPoolArray::get(cast<ArrayType>(CPA->getType()), Operands);
67 } else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CPV)) {
68 const vector<Use> &Ops = CPS->getValues();
69 vector<ConstPoolVal*> Operands(Ops.size());
70 for (unsigned i = 0; i < Ops.size(); ++i)
72 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
73 Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
74 } else if (isa<ConstPoolPointerNull>(CPV)) {
76 } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(CPV)) {
77 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
78 Result = ConstPoolPointerRef::get(cast<GlobalValue>(V));
80 assert(0 && "Unknown type of derived type constant value!");
83 // Cache the mapping in our local map structure...
84 LocalMap.insert(make_pair(In, CPV));
88 cerr << "XXX LocalMap: \n";
92 cerr << "XXX GlobalMap: \n";
96 cerr << "Couldn't remap value: " << (void*)In << " " << In << endl;
97 assert(0 && "Couldn't remap value!");
102 // LinkGlobals - Loop through the global variables in the src module and merge
103 // them into the dest module...
105 static bool LinkGlobals(Module *Dest, const Module *Src,
106 map<const Value*, Value*> &ValueMap, string *Err = 0) {
107 // We will need a module level symbol table if the src module has a module
108 // level symbol table...
109 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
111 // Loop over all of the globals in the src module, mapping them over as we go
113 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
114 const GlobalVariable *SGV = *I;
117 // If the global variable has a name, and that name is already in use in the
118 // Dest module, make sure that the name is a compatible global variable...
120 if (SGV->hasName() && (V = ST->lookup(SGV->getType(), SGV->getName()))) {
121 // The same named thing is a global variable, because the only two things
122 // that may be in a module level symbol table are Global Vars and Methods,
123 // and they both have distinct, nonoverlapping, possible types.
125 GlobalVariable *DGV = cast<GlobalVariable>(V);
127 // Check to see if the two GV's have the same Const'ness...
128 if (SGV->isConstant() != DGV->isConstant())
129 return Error(Err, "Global Variable Collision on '" +
130 SGV->getType()->getDescription() + "':%" + SGV->getName() +
131 " - Global variables differ in const'ness");
133 // Okay, everything is cool, remember the mapping...
134 ValueMap.insert(make_pair(SGV, DGV));
136 // No linking to be performed, simply create an identical version of the
137 // symbol over in the dest module... the initializer will be filled in
138 // later by LinkGlobalInits...
140 GlobalVariable *DGV =
141 new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
144 // Add the new global to the dest module
145 Dest->getGlobalList().push_back(DGV);
147 // Make sure to remember this mapping...
148 ValueMap.insert(make_pair(SGV, DGV));
155 // LinkGlobalInits - Update the initializers in the Dest module now that all
156 // globals that may be referenced are in Dest.
158 static bool LinkGlobalInits(Module *Dest, const Module *Src,
159 map<const Value*, Value*> &ValueMap,
162 // Loop over all of the globals in the src module, mapping them over as we go
164 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
165 const GlobalVariable *SGV = *I;
167 if (SGV->hasInitializer()) { // Only process initialized GV's
168 // Figure out what the initializer looks like in the dest module...
169 ConstPoolVal *DInit =
170 cast<ConstPoolVal>(RemapOperand(SGV->getInitializer(), ValueMap));
172 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
173 if (DGV->hasInitializer()) {
174 if (DGV->getInitializer() != DInit)
175 return Error(Err, "Global Variable Collision on '" +
176 SGV->getType()->getDescription() + "':%" +SGV->getName()+
177 " - Global variables have different initializers");
179 // Copy the initializer over now...
180 DGV->setInitializer(DInit);
187 // LinkMethodProtos - Link the methods together between the two modules, without
188 // doing method bodies... this just adds external method prototypes to the Dest
191 static bool LinkMethodProtos(Module *Dest, const Module *Src,
192 map<const Value*, Value*> &ValueMap,
194 // We will need a module level symbol table if the src module has a module
195 // level symbol table...
196 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
198 // Loop over all of the methods in the src module, mapping them over as we go
200 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
201 const Method *SM = *I; // SrcMethod
204 // If the method has a name, and that name is already in use in the
205 // Dest module, make sure that the name is a compatible method...
207 if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
208 // The same named thing is a Method, because the only two things
209 // that may be in a module level symbol table are Global Vars and Methods,
210 // and they both have distinct, nonoverlapping, possible types.
212 Method *DM = cast<Method>(V); // DestMethod
214 // Check to make sure the method is not defined in both modules...
215 if (!SM->isExternal() && !DM->isExternal())
216 return Error(Err, "Method '" +
217 SM->getMethodType()->getDescription() + "':\"" +
218 SM->getName() + "\" - Method is already defined!");
220 // Otherwise, just remember this mapping...
221 ValueMap.insert(make_pair(SM, DM));
223 // Method does not already exist, simply insert an external method
224 // signature identical to SM into the dest module...
225 Method *DM = new Method(SM->getMethodType(), SM->getName());
227 // Add the method signature to the dest module...
228 Dest->getMethodList().push_back(DM);
230 // ... and remember this mapping...
231 ValueMap.insert(make_pair(SM, DM));
237 // LinkMethodBody - Copy the source method over into the dest method and fix up
238 // references to values. At this point we know that Dest is an external method,
239 // and that Src is not.
241 static bool LinkMethodBody(Method *Dest, const Method *Src,
242 const map<const Value*, Value*> &GlobalMap,
244 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
245 map<const Value*, Value*> LocalMap; // Map for method local values
247 // Go through and convert method arguments over...
248 for (Method::ArgumentListType::const_iterator
249 I = Src->getArgumentList().begin(),
250 E = Src->getArgumentList().end(); I != E; ++I) {
251 const MethodArgument *SMA = *I;
253 // Create the new method argument and add to the dest method...
254 MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
255 Dest->getArgumentList().push_back(DMA);
257 // Add a mapping to our local map
258 LocalMap.insert(make_pair(SMA, DMA));
261 // Loop over all of the basic blocks, copying the instructions over...
263 for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
264 const BasicBlock *SBB = *I;
266 // Create new basic block and add to mapping and the Dest method...
267 BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
268 LocalMap.insert(make_pair(SBB, DBB));
270 // Loop over all of the instructions in the src basic block, copying them
271 // over. Note that this is broken in a strict sense because the cloned
272 // instructions will still be referencing values in the Src module, not
273 // the remapped values. In our case, however, we will not get caught and
274 // so we can delay patching the values up until later...
276 for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end();
278 const Instruction *SI = *II;
279 Instruction *DI = SI->clone();
280 DI->setName(SI->getName());
281 DBB->getInstList().push_back(DI);
282 LocalMap.insert(make_pair(SI, DI));
286 // At this point, all of the instructions and values of the method are now
287 // copied over. The only problem is that they are still referencing values
288 // in the Source method as operands. Loop through all of the operands of the
289 // methods and patch them up to point to the local versions...
291 for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
293 Instruction *Inst = *I;
295 for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
297 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
304 // LinkMethodBodies - Link in the method bodies that are defined in the source
305 // module into the DestModule. This consists basically of copying the method
306 // over and fixing up references to values.
308 static bool LinkMethodBodies(Module *Dest, const Module *Src,
309 map<const Value*, Value*> &ValueMap,
312 // Loop over all of the methods in the src module, mapping them over as we go
314 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
315 const Method *SM = *I; // Source Method
316 if (!SM->isExternal()) { // No body if method is external
317 Method *DM = cast<Method>(ValueMap[SM]); // Destination method
319 // DM not external SM external?
320 if (!DM->isExternal()) {
322 *Err = "Method '" + (SM->hasName() ? SM->getName() : string("")) +
323 "' body multiply defined!";
327 if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
335 // LinkModules - This function links two modules together, with the resulting
336 // left module modified to be the composite of the two input modules. If an
337 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
338 // the problem. Upon failure, the Dest module could be in a modified state, and
339 // shouldn't be relied on to be consistent.
341 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
342 // ValueMap - Mapping of values from what they used to be in Src, to what they
345 map<const Value*, Value*> ValueMap;
347 // Insert all of the globals in src into the Dest module... without
349 if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
351 // Update the initializers in the Dest module now that all globals that may
352 // be referenced are in Dest.
354 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
356 // Link the methods together between the two modules, without doing method
357 // bodies... this just adds external method prototypes to the Dest method...
358 // We do this so that when we begin processing method bodies, all of the
359 // global values that may be referenced are available in our ValueMap.
361 if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
363 // Link in the method bodies that are defined in the source module into the
364 // DestModule. This consists basically of copying the method over and fixing
365 // up references to values.
367 if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;