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
31 // LinkTypes - Go through the symbol table of the Src module and see if any
32 // types are named in the src module that are not named in the Dst module.
33 // Make sure there are no type name conflicts.
35 static bool LinkTypes(Module *Dest, const Module *Src, string *Err = 0) {
36 // No symbol table? Can't have named types.
37 if (!Src->hasSymbolTable()) return false;
39 SymbolTable *DestST = Dest->getSymbolTableSure();
40 const SymbolTable *SrcST = Src->getSymbolTable();
42 // Look for a type plane for Type's...
43 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
44 if (PI == SrcST->end()) return false; // No named types, do nothing.
46 const SymbolTable::VarMap &VM = PI->second;
47 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
49 const string &Name = I->first;
50 const Type *RHS = cast<Type>(I->second);
52 // Check to see if this type name is already in the dest module...
53 const Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
54 if (Entry) { // Yup, the value already exists...
55 if (Entry != RHS) // If it's the same, noop. Otherwise, error.
56 return Error(Err, "Type named '" + Name +
57 "' of different shape in modules.\n Src='" +
58 Entry->getDescription() + "'. Dest='" +
59 RHS->getDescription() + "'");
60 } else { // Type not in dest module. Add it now.
61 // TODO: FIXME WHEN TYPES AREN'T CONST
62 DestST->insert(Name, const_cast<Type*>(RHS));
68 static void PrintMap(const map<const Value*, Value*> &M) {
69 for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
71 cerr << " Fr: " << (void*)I->first << " " << I->first
72 << " To: " << (void*)I->second << " " << I->second << endl;
77 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
78 // module to another. This is somewhat sophisticated in that it can
79 // automatically handle constant references correctly as well...
81 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
82 const map<const Value*, Value*> *GlobalMap = 0) {
83 map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
84 if (I != LocalMap.end()) return I->second;
87 I = GlobalMap->find(In);
88 if (I != GlobalMap->end()) return I->second;
91 // Check to see if it's a constant that we are interesting in transforming...
92 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(In)) {
93 if (!isa<DerivedType>(CPV->getType()))
94 return CPV; // Simple constants stay identical...
96 ConstPoolVal *Result = 0;
98 if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CPV)) {
99 const vector<Use> &Ops = CPA->getValues();
100 vector<ConstPoolVal*> Operands(Ops.size());
101 for (unsigned i = 0; i < Ops.size(); ++i)
103 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
104 Result = ConstPoolArray::get(cast<ArrayType>(CPA->getType()), Operands);
105 } else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CPV)) {
106 const vector<Use> &Ops = CPS->getValues();
107 vector<ConstPoolVal*> Operands(Ops.size());
108 for (unsigned i = 0; i < Ops.size(); ++i)
110 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
111 Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
112 } else if (isa<ConstPoolPointerNull>(CPV)) {
114 } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(CPV)) {
115 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
116 Result = ConstPoolPointerRef::get(cast<GlobalValue>(V));
118 assert(0 && "Unknown type of derived type constant value!");
121 // Cache the mapping in our local map structure...
122 LocalMap.insert(make_pair(In, CPV));
126 cerr << "XXX LocalMap: \n";
130 cerr << "XXX GlobalMap: \n";
131 PrintMap(*GlobalMap);
134 cerr << "Couldn't remap value: " << (void*)In << " " << In << endl;
135 assert(0 && "Couldn't remap value!");
140 // LinkGlobals - Loop through the global variables in the src module and merge
141 // them into the dest module...
143 static bool LinkGlobals(Module *Dest, const Module *Src,
144 map<const Value*, Value*> &ValueMap, string *Err = 0) {
145 // We will need a module level symbol table if the src module has a module
146 // level symbol table...
147 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
149 // Loop over all of the globals in the src module, mapping them over as we go
151 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
152 const GlobalVariable *SGV = *I;
155 // If the global variable has a name, and that name is already in use in the
156 // Dest module, make sure that the name is a compatible global variable...
158 if (SGV->hasName() && (V = ST->lookup(SGV->getType(), SGV->getName()))) {
159 // The same named thing is a global variable, because the only two things
160 // that may be in a module level symbol table are Global Vars and Methods,
161 // and they both have distinct, nonoverlapping, possible types.
163 GlobalVariable *DGV = cast<GlobalVariable>(V);
165 // Check to see if the two GV's have the same Const'ness...
166 if (SGV->isConstant() != DGV->isConstant())
167 return Error(Err, "Global Variable Collision on '" +
168 SGV->getType()->getDescription() + "':%" + SGV->getName() +
169 " - Global variables differ in const'ness");
171 // Okay, everything is cool, remember the mapping...
172 ValueMap.insert(make_pair(SGV, DGV));
174 // No linking to be performed, simply create an identical version of the
175 // symbol over in the dest module... the initializer will be filled in
176 // later by LinkGlobalInits...
178 GlobalVariable *DGV =
179 new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
182 // Add the new global to the dest module
183 Dest->getGlobalList().push_back(DGV);
185 // Make sure to remember this mapping...
186 ValueMap.insert(make_pair(SGV, DGV));
193 // LinkGlobalInits - Update the initializers in the Dest module now that all
194 // globals that may be referenced are in Dest.
196 static bool LinkGlobalInits(Module *Dest, const Module *Src,
197 map<const Value*, Value*> &ValueMap,
200 // Loop over all of the globals in the src module, mapping them over as we go
202 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
203 const GlobalVariable *SGV = *I;
205 if (SGV->hasInitializer()) { // Only process initialized GV's
206 // Figure out what the initializer looks like in the dest module...
207 ConstPoolVal *DInit =
208 cast<ConstPoolVal>(RemapOperand(SGV->getInitializer(), ValueMap));
210 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
211 if (DGV->hasInitializer()) {
212 if (DGV->getInitializer() != DInit)
213 return Error(Err, "Global Variable Collision on '" +
214 SGV->getType()->getDescription() + "':%" +SGV->getName()+
215 " - Global variables have different initializers");
217 // Copy the initializer over now...
218 DGV->setInitializer(DInit);
225 // LinkMethodProtos - Link the methods together between the two modules, without
226 // doing method bodies... this just adds external method prototypes to the Dest
229 static bool LinkMethodProtos(Module *Dest, const Module *Src,
230 map<const Value*, Value*> &ValueMap,
232 // We will need a module level symbol table if the src module has a module
233 // level symbol table...
234 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
236 // Loop over all of the methods in the src module, mapping them over as we go
238 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
239 const Method *SM = *I; // SrcMethod
242 // If the method has a name, and that name is already in use in the
243 // Dest module, make sure that the name is a compatible method...
245 if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
246 // The same named thing is a Method, because the only two things
247 // that may be in a module level symbol table are Global Vars and Methods,
248 // and they both have distinct, nonoverlapping, possible types.
250 Method *DM = cast<Method>(V); // DestMethod
252 // Check to make sure the method is not defined in both modules...
253 if (!SM->isExternal() && !DM->isExternal())
254 return Error(Err, "Method '" +
255 SM->getMethodType()->getDescription() + "':\"" +
256 SM->getName() + "\" - Method is already defined!");
258 // Otherwise, just remember this mapping...
259 ValueMap.insert(make_pair(SM, DM));
261 // Method does not already exist, simply insert an external method
262 // signature identical to SM into the dest module...
263 Method *DM = new Method(SM->getMethodType(), SM->getName());
265 // Add the method signature to the dest module...
266 Dest->getMethodList().push_back(DM);
268 // ... and remember this mapping...
269 ValueMap.insert(make_pair(SM, DM));
275 // LinkMethodBody - Copy the source method over into the dest method and fix up
276 // references to values. At this point we know that Dest is an external method,
277 // and that Src is not.
279 static bool LinkMethodBody(Method *Dest, const Method *Src,
280 const map<const Value*, Value*> &GlobalMap,
282 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
283 map<const Value*, Value*> LocalMap; // Map for method local values
285 // Go through and convert method arguments over...
286 for (Method::ArgumentListType::const_iterator
287 I = Src->getArgumentList().begin(),
288 E = Src->getArgumentList().end(); I != E; ++I) {
289 const MethodArgument *SMA = *I;
291 // Create the new method argument and add to the dest method...
292 MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
293 Dest->getArgumentList().push_back(DMA);
295 // Add a mapping to our local map
296 LocalMap.insert(make_pair(SMA, DMA));
299 // Loop over all of the basic blocks, copying the instructions over...
301 for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
302 const BasicBlock *SBB = *I;
304 // Create new basic block and add to mapping and the Dest method...
305 BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
306 LocalMap.insert(make_pair(SBB, DBB));
308 // Loop over all of the instructions in the src basic block, copying them
309 // over. Note that this is broken in a strict sense because the cloned
310 // instructions will still be referencing values in the Src module, not
311 // the remapped values. In our case, however, we will not get caught and
312 // so we can delay patching the values up until later...
314 for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end();
316 const Instruction *SI = *II;
317 Instruction *DI = SI->clone();
318 DI->setName(SI->getName());
319 DBB->getInstList().push_back(DI);
320 LocalMap.insert(make_pair(SI, DI));
324 // At this point, all of the instructions and values of the method are now
325 // copied over. The only problem is that they are still referencing values
326 // in the Source method as operands. Loop through all of the operands of the
327 // methods and patch them up to point to the local versions...
329 for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
331 Instruction *Inst = *I;
333 for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
335 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
342 // LinkMethodBodies - Link in the method bodies that are defined in the source
343 // module into the DestModule. This consists basically of copying the method
344 // over and fixing up references to values.
346 static bool LinkMethodBodies(Module *Dest, const Module *Src,
347 map<const Value*, Value*> &ValueMap,
350 // Loop over all of the methods in the src module, mapping them over as we go
352 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
353 const Method *SM = *I; // Source Method
354 if (!SM->isExternal()) { // No body if method is external
355 Method *DM = cast<Method>(ValueMap[SM]); // Destination method
357 // DM not external SM external?
358 if (!DM->isExternal()) {
360 *Err = "Method '" + (SM->hasName() ? SM->getName() : string("")) +
361 "' body multiply defined!";
365 if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
373 // LinkModules - This function links two modules together, with the resulting
374 // left module modified to be the composite of the two input modules. If an
375 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
376 // the problem. Upon failure, the Dest module could be in a modified state, and
377 // shouldn't be relied on to be consistent.
379 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
381 // LinkTypes - Go through the symbol table of the Src module and see if any
382 // types are named in the src module that are not named in the Dst module.
383 // Make sure there are no type name conflicts.
385 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
387 // ValueMap - Mapping of values from what they used to be in Src, to what they
390 map<const Value*, Value*> ValueMap;
392 // Insert all of the globals in src into the Dest module... without
394 if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
396 // Update the initializers in the Dest module now that all globals that may
397 // be referenced are in Dest.
399 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
401 // Link the methods together between the two modules, without doing method
402 // bodies... this just adds external method prototypes to the Dest method...
403 // We do this so that when we begin processing method bodies, all of the
404 // global values that may be referenced are available in our ValueMap.
406 if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
408 // Link in the method bodies that are defined in the source module into the
409 // DestModule. This consists basically of copying the method over and fixing
410 // up references to values.
412 if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;