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 functions between two modules
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Transforms/Utils/Linker.h"
13 #include "llvm/Module.h"
14 #include "llvm/SymbolTable.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/iOther.h"
17 #include "llvm/Constants.h"
22 // Error - Simple wrapper function to conditionally assign to E and return true.
23 // This just makes error return conditions a little bit simpler...
25 static inline bool Error(string *E, string Message) {
30 // LinkTypes - Go through the symbol table of the Src module and see if any
31 // types are named in the src module that are not named in the Dst module.
32 // Make sure there are no type name conflicts.
34 static bool LinkTypes(Module *Dest, const Module *Src, string *Err = 0) {
35 // No symbol table? Can't have named types.
36 if (!Src->hasSymbolTable()) return false;
38 SymbolTable *DestST = Dest->getSymbolTableSure();
39 const SymbolTable *SrcST = Src->getSymbolTable();
41 // Look for a type plane for Type's...
42 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
43 if (PI == SrcST->end()) return false; // No named types, do nothing.
45 const SymbolTable::VarMap &VM = PI->second;
46 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
48 const string &Name = I->first;
49 const Type *RHS = cast<Type>(I->second);
51 // Check to see if this type name is already in the dest module...
52 const Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
53 if (Entry) { // Yup, the value already exists...
54 if (Entry != RHS) // If it's the same, noop. Otherwise, error.
55 return Error(Err, "Type named '" + Name +
56 "' of different shape in modules.\n Src='" +
57 Entry->getDescription() + "'.\n Dst='" +
58 RHS->getDescription() + "'");
59 } else { // Type not in dest module. Add it now.
60 // TODO: FIXME WHEN TYPES AREN'T CONST
61 DestST->insert(Name, const_cast<Type*>(RHS));
67 static void PrintMap(const map<const Value*, Value*> &M) {
68 for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
70 cerr << " Fr: " << (void*)I->first << " ";
72 cerr << " To: " << (void*)I->second << " ";
79 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
80 // module to another. This is somewhat sophisticated in that it can
81 // automatically handle constant references correctly as well...
83 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
84 map<const Value*, Value*> *GlobalMap = 0) {
85 map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
86 if (I != LocalMap.end()) return I->second;
89 I = GlobalMap->find(In);
90 if (I != GlobalMap->end()) return I->second;
93 // Check to see if it's a constant that we are interesting in transforming...
94 if (const Constant *CPV = dyn_cast<Constant>(In)) {
95 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
96 return const_cast<Constant*>(CPV); // Simple constants stay identical...
100 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
101 const std::vector<Use> &Ops = CPA->getValues();
102 std::vector<Constant*> Operands(Ops.size());
103 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
105 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
106 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
107 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
108 const std::vector<Use> &Ops = CPS->getValues();
109 std::vector<Constant*> Operands(Ops.size());
110 for (unsigned i = 0; i < Ops.size(); ++i)
112 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
113 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
114 } else if (isa<ConstantPointerNull>(CPV)) {
115 Result = const_cast<Constant*>(CPV);
116 } else if (const ConstantPointerRef *CPR =
117 dyn_cast<ConstantPointerRef>(CPV)) {
118 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
119 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
120 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
121 if (CE->getOpcode() == Instruction::GetElementPtr) {
122 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
123 std::vector<Constant*> Indices;
124 Indices.reserve(CE->getNumOperands()-1);
125 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
126 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
127 LocalMap, GlobalMap)));
129 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
130 } else if (CE->getNumOperands() == 1) {
132 assert(CE->getOpcode() == Instruction::Cast);
133 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
134 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
135 } else if (CE->getNumOperands() == 2) {
136 // Binary operator...
137 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
138 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
140 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
143 assert(0 && "Unknown constant expr type!");
147 assert(0 && "Unknown type of derived type constant value!");
150 // Cache the mapping in our local map structure...
152 GlobalMap->insert(std::make_pair(In, Result));
154 LocalMap.insert(std::make_pair(In, Result));
158 cerr << "XXX LocalMap: \n";
162 cerr << "XXX GlobalMap: \n";
163 PrintMap(*GlobalMap);
166 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
167 assert(0 && "Couldn't remap value!");
172 // LinkGlobals - Loop through the global variables in the src module and merge
173 // them into the dest module...
175 static bool LinkGlobals(Module *Dest, const Module *Src,
176 map<const Value*, Value*> &ValueMap, 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;
181 // Loop over all of the globals in the src module, mapping them over as we go
183 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
184 const GlobalVariable *SGV = I;
187 // If the global variable has a name, and that name is already in use in the
188 // Dest module, make sure that the name is a compatible global variable...
190 if (SGV->hasExternalLinkage() && SGV->hasName() &&
191 (V = ST->lookup(SGV->getType(), SGV->getName())) &&
192 cast<GlobalVariable>(V)->hasExternalLinkage()) {
193 // The same named thing is a global variable, because the only two things
194 // that may be in a module level symbol table are Global Vars and
195 // Functions, and they both have distinct, nonoverlapping, possible types.
197 GlobalVariable *DGV = cast<GlobalVariable>(V);
199 // Check to see if the two GV's have the same Const'ness...
200 if (SGV->isConstant() != DGV->isConstant())
201 return Error(Err, "Global Variable Collision on '" +
202 SGV->getType()->getDescription() + "':%" + SGV->getName() +
203 " - Global variables differ in const'ness");
205 // Okay, everything is cool, remember the mapping...
206 ValueMap.insert(std::make_pair(SGV, DGV));
208 // No linking to be performed, simply create an identical version of the
209 // symbol over in the dest module... the initializer will be filled in
210 // later by LinkGlobalInits...
212 GlobalVariable *DGV =
213 new GlobalVariable(SGV->getType()->getElementType(), SGV->isConstant(),
214 SGV->hasInternalLinkage(), 0, SGV->getName());
216 // Add the new global to the dest module
217 Dest->getGlobalList().push_back(DGV);
219 // Make sure to remember this mapping...
220 ValueMap.insert(std::make_pair(SGV, DGV));
227 // LinkGlobalInits - Update the initializers in the Dest module now that all
228 // globals that may be referenced are in Dest.
230 static bool LinkGlobalInits(Module *Dest, const Module *Src,
231 map<const Value*, Value*> &ValueMap,
234 // Loop over all of the globals in the src module, mapping them over as we go
236 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
237 const GlobalVariable *SGV = I;
239 if (SGV->hasInitializer()) { // Only process initialized GV's
240 // Figure out what the initializer looks like in the dest module...
242 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
244 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
245 if (DGV->hasInitializer() && SGV->hasExternalLinkage() &&
246 DGV->hasExternalLinkage()) {
247 if (DGV->getInitializer() != DInit)
248 return Error(Err, "Global Variable Collision on '" +
249 SGV->getType()->getDescription() + "':%" +SGV->getName()+
250 " - Global variables have different initializers");
252 // Copy the initializer over now...
253 DGV->setInitializer(DInit);
260 // LinkFunctionProtos - Link the functions together between the two modules,
261 // without doing function bodies... this just adds external function prototypes
262 // to the Dest function...
264 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
265 map<const Value*, Value*> &ValueMap,
267 // We will need a module level symbol table if the src module has a module
268 // level symbol table...
269 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
271 // Loop over all of the functions in the src module, mapping them over as we
274 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
275 const Function *SF = I; // SrcFunction
278 // If the function has a name, and that name is already in use in the Dest
279 // module, make sure that the name is a compatible function...
281 if (SF->hasExternalLinkage() && SF->hasName() &&
282 (V = ST->lookup(SF->getType(), SF->getName())) &&
283 cast<Function>(V)->hasExternalLinkage()) {
284 // The same named thing is a Function, because the only two things
285 // that may be in a module level symbol table are Global Vars and
286 // Functions, and they both have distinct, nonoverlapping, possible types.
288 Function *DF = cast<Function>(V); // DestFunction
290 // Check to make sure the function is not defined in both modules...
291 if (!SF->isExternal() && !DF->isExternal())
292 return Error(Err, "Function '" +
293 SF->getFunctionType()->getDescription() + "':\"" +
294 SF->getName() + "\" - Function is already defined!");
296 // Otherwise, just remember this mapping...
297 ValueMap.insert(std::make_pair(SF, DF));
299 // Function does not already exist, simply insert an external function
300 // signature identical to SF into the dest module...
301 Function *DF = new Function(SF->getFunctionType(),
302 SF->hasInternalLinkage(),
305 // Add the function signature to the dest module...
306 Dest->getFunctionList().push_back(DF);
308 // ... and remember this mapping...
309 ValueMap.insert(std::make_pair(SF, DF));
315 // LinkFunctionBody - Copy the source function over into the dest function and
316 // fix up references to values. At this point we know that Dest is an external
317 // function, and that Src is not.
319 static bool LinkFunctionBody(Function *Dest, const Function *Src,
320 map<const Value*, Value*> &GlobalMap,
322 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
323 map<const Value*, Value*> LocalMap; // Map for function local values
325 // Go through and convert function arguments over...
326 Function::aiterator DI = Dest->abegin();
327 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
329 DI->setName(I->getName()); // Copy the name information over...
331 // Add a mapping to our local map
332 LocalMap.insert(std::make_pair(I, DI));
335 // Loop over all of the basic blocks, copying the instructions over...
337 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
338 // Create new basic block and add to mapping and the Dest function...
339 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
340 LocalMap.insert(std::make_pair(I, DBB));
342 // Loop over all of the instructions in the src basic block, copying them
343 // over. Note that this is broken in a strict sense because the cloned
344 // instructions will still be referencing values in the Src module, not
345 // the remapped values. In our case, however, we will not get caught and
346 // so we can delay patching the values up until later...
348 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
350 Instruction *DI = II->clone();
351 DI->setName(II->getName());
352 DBB->getInstList().push_back(DI);
353 LocalMap.insert(std::make_pair(II, DI));
357 // At this point, all of the instructions and values of the function are now
358 // copied over. The only problem is that they are still referencing values in
359 // the Source function as operands. Loop through all of the operands of the
360 // functions and patch them up to point to the local versions...
362 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
363 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
364 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
366 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
372 // LinkFunctionBodies - Link in the function bodies that are defined in the
373 // source module into the DestModule. This consists basically of copying the
374 // function over and fixing up references to values.
376 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
377 map<const Value*, Value*> &ValueMap,
380 // Loop over all of the functions in the src module, mapping them over as we
383 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
384 if (!SF->isExternal()) { // No body if function is external
385 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
387 // DF not external SF external?
388 if (!DF->isExternal()) {
390 *Err = "Function '" + (SF->hasName() ? SF->getName() : string("")) +
391 "' body multiply defined!";
395 if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
403 // LinkModules - This function links two modules together, with the resulting
404 // left module modified to be the composite of the two input modules. If an
405 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
406 // the problem. Upon failure, the Dest module could be in a modified state, and
407 // shouldn't be relied on to be consistent.
409 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg) {
411 // LinkTypes - Go through the symbol table of the Src module and see if any
412 // types are named in the src module that are not named in the Dst module.
413 // Make sure there are no type name conflicts.
415 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
417 // ValueMap - Mapping of values from what they used to be in Src, to what they
420 map<const Value*, Value*> ValueMap;
422 // Insert all of the globals in src into the Dest module... without
424 if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
426 // Link the functions together between the two modules, without doing function
427 // bodies... this just adds external function prototypes to the Dest
428 // function... We do this so that when we begin processing function bodies,
429 // all of the global values that may be referenced are available in our
432 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
434 // Update the initializers in the Dest module now that all globals that may
435 // be referenced are in Dest.
437 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
439 // Link in the function bodies that are defined in the source module into the
440 // DestModule. This consists basically of copying the function over and
441 // fixing up references to values.
443 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;