Added name-mangling routines for future use.
[oota-llvm.git] / lib / Linker / LinkModules.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 //  * 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 #include "string"
20
21
22 // Error - Simple wrapper function to conditionally assign to E and return true.
23 // This just makes error return conditions a little bit simpler...
24 //
25 static inline bool Error(string *E, string Message) {
26   if (E) *E = Message;
27   return true;
28 }
29
30 #include "llvm/Assembly/Writer.h" // TODO: REMOVE
31
32 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
33 // module to another.  This is somewhat sophisticated in that it can
34 // automatically handle constant references correctly as well...
35 //
36 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
37                            const map<const Value*, Value*> *GlobalMap = 0) {
38   map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
39   if (I != LocalMap.end()) return I->second;
40
41   if (GlobalMap) {
42     I = GlobalMap->find(In);
43     if (I != GlobalMap->end()) return I->second;
44   }
45
46   // Check to see if it's a constant that we are interesting in transforming...
47   if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(In)) {
48     if (!isa<DerivedType>(CPV->getType()))
49       return CPV;              // Simple constants stay identical...
50
51     ConstPoolVal *Result = 0;
52
53     if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CPV)) {
54       const vector<Use> &Ops = CPA->getValues();
55       vector<ConstPoolVal*> Operands(Ops.size());
56       for (unsigned i = 0; i < Ops.size(); ++i)
57         Operands[i] = 
58           cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
59       Result = ConstPoolArray::get(cast<ArrayType>(CPA->getType()), Operands);
60     } else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CPV)) {
61       const vector<Use> &Ops = CPS->getValues();
62       vector<ConstPoolVal*> Operands(Ops.size());
63       for (unsigned i = 0; i < Ops.size(); ++i)
64         Operands[i] = 
65           cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
66       Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
67     } else if (isa<ConstPoolPointerNull>(CPV)) {
68       Result = CPV;
69     } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(CPV)) {
70       Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
71       Result = ConstPoolPointerRef::get(cast<GlobalValue>(V));
72     } else {
73       assert(0 && "Unknown type of derived type constant value!");
74     }
75
76     // Cache the mapping in our local map structure...
77     LocalMap.insert(make_pair(In, CPV));
78     return Result;
79   }
80   
81   cerr << "Couldn't remap value: " << In << endl;
82   assert(0 && "Couldn't remap value!");
83   return 0;
84 }
85
86
87 // LinkGlobals - Loop through the global variables in the src module and merge
88 // them into the dest module...
89 //
90 static bool LinkGlobals(Module *Dest, const Module *Src,
91                         map<const Value*, Value*> &ValueMap, string *Err = 0) {
92   // We will need a module level symbol table if the src module has a module
93   // level symbol table...
94   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
95   
96   // Loop over all of the globals in the src module, mapping them over as we go
97   //
98   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
99     const GlobalVariable *SGV = *I;
100     Value *V;
101
102     // If the global variable has a name, and that name is already in use in the
103     // Dest module, make sure that the name is a compatible global variable...
104     //
105     if (SGV->hasName() && (V = ST->lookup(SGV->getType(), SGV->getName()))) {
106       // The same named thing is a global variable, because the only two things
107       // that may be in a module level symbol table are Global Vars and Methods,
108       // and they both have distinct, nonoverlapping, possible types.
109       // 
110       GlobalVariable *DGV = cast<GlobalVariable>(V);
111
112       // Check to see if the two GV's have the same Const'ness...
113       if (SGV->isConstant() != DGV->isConstant())
114         return Error(Err, "Global Variable Collision on '" + 
115                      SGV->getType()->getDescription() + "':%" + SGV->getName() +
116                      " - Global variables differ in const'ness");
117
118       // Okay, everything is cool, remember the mapping...
119       ValueMap.insert(make_pair(SGV, DGV));
120     } else {
121       // No linking to be performed, simply create an identical version of the
122       // symbol over in the dest module... the initializer will be filled in
123       // later by LinkGlobalInits...
124       //
125       GlobalVariable *DGV = 
126         new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
127                            0, SGV->getName());
128
129       // Add the new global to the dest module
130       Dest->getGlobalList().push_back(DGV);
131
132       // Make sure to remember this mapping...
133       ValueMap.insert(make_pair(SGV, DGV));
134     }
135   }
136   return false;
137 }
138
139
140 // LinkGlobalInits - Update the initializers in the Dest module now that all
141 // globals that may be referenced are in Dest.
142 //
143 static bool LinkGlobalInits(Module *Dest, const Module *Src,
144                             map<const Value*, Value*> &ValueMap,
145                             string *Err = 0) {
146
147   // Loop over all of the globals in the src module, mapping them over as we go
148   //
149   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
150     const GlobalVariable *SGV = *I;
151
152     if (SGV->hasInitializer()) {      // Only process initialized GV's
153       // Figure out what the initializer looks like in the dest module...
154       ConstPoolVal *DInit =
155         cast<ConstPoolVal>(RemapOperand(SGV->getInitializer(), ValueMap));
156
157       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
158       if (DGV->hasInitializer()) {
159         if (DGV->getInitializer() != DInit)
160           return Error(Err, "Global Variable Collision on '" + 
161                        SGV->getType()->getDescription() + "':%" +SGV->getName()+
162                        " - Global variables have different initializers");
163       } else {
164         // Copy the initializer over now...
165         DGV->setInitializer(DInit);
166       }
167     }
168   }
169   return false;
170 }
171
172 // LinkMethodProtos - Link the methods together between the two modules, without
173 // doing method bodies... this just adds external method prototypes to the Dest
174 // method...
175 //
176 static bool LinkMethodProtos(Module *Dest, const Module *Src,
177                              map<const Value*, Value*> &ValueMap,
178                              string *Err = 0) {
179   // We will need a module level symbol table if the src module has a module
180   // level symbol table...
181   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
182   
183   // Loop over all of the methods in the src module, mapping them over as we go
184   //
185   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
186     const Method *SM = *I;   // SrcMethod
187     Value *V;
188
189     // If the method has a name, and that name is already in use in the
190     // Dest module, make sure that the name is a compatible method...
191     //
192     if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
193       // The same named thing is a Method, because the only two things
194       // that may be in a module level symbol table are Global Vars and Methods,
195       // and they both have distinct, nonoverlapping, possible types.
196       // 
197       Method *DM = cast<Method>(V);   // DestMethod
198
199       // Check to make sure the method is not defined in both modules...
200       if (!SM->isExternal() && !DM->isExternal())
201         return Error(Err, "Method '" + 
202                      SM->getMethodType()->getDescription() + "':\"" + 
203                      SM->getName() + "\" - Method is already defined!");
204
205       // Otherwise, just remember this mapping...
206       ValueMap.insert(make_pair(SM, DM));
207     } else {
208       // Method does not already exist, simply insert an external method
209       // signature identical to SM into the dest module...
210       Method *DM = new Method(SM->getMethodType(), SM->getName());
211
212       // Add the method signature to the dest module...
213       Dest->getMethodList().push_back(DM);
214
215       // ... and remember this mapping...
216       ValueMap.insert(make_pair(SM, DM));
217     }
218   }
219   return false;
220 }
221
222 // LinkMethodBody - Copy the source method over into the dest method and fix up
223 // references to values.  At this point we know that Dest is an external method,
224 // and that Src is not.
225 //
226 static bool LinkMethodBody(Method *Dest, const Method *Src,
227                            const map<const Value*, Value*> &GlobalMap,
228                            string *Err = 0) {
229   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
230   map<const Value*, Value*> LocalMap;   // Map for method local values
231
232   // Go through and convert method arguments over...
233   for (Method::ArgumentListType::const_iterator 
234          I = Src->getArgumentList().begin(),
235          E = Src->getArgumentList().end(); I != E; ++I) {
236     const MethodArgument *SMA = *I;
237
238     // Create the new method argument and add to the dest method...
239     MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
240     Dest->getArgumentList().push_back(DMA);
241
242     // Add a mapping to our local map
243     LocalMap.insert(make_pair(SMA, DMA));
244   }
245
246   // Loop over all of the basic blocks, copying the instructions over...
247   //
248   for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
249     const BasicBlock *SBB = *I;
250
251     // Create new basic block and add to mapping and the Dest method...
252     BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
253     LocalMap.insert(make_pair(SBB, DBB));
254
255     // Loop over all of the instructions in the src basic block, copying them
256     // over.  Note that this is broken in a strict sense because the cloned
257     // instructions will still be referencing values in the Src module, not
258     // the remapped values.  In our case, however, we will not get caught and 
259     // so we can delay patching the values up until later...
260     //
261     for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end(); 
262          II != IE; ++II) {
263       const Instruction *SI = *II;
264       Instruction *DI = SI->clone();
265       DBB->getInstList().push_back(DI);
266       LocalMap.insert(make_pair(SI, DI));
267     }
268   }
269
270   // At this point, all of the instructions and values of the method are now
271   // copied over.  The only problem is that they are still referencing values
272   // in the Source method as operands.  Loop through all of the operands of the
273   // methods and patch them up to point to the local versions...
274   //
275   for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
276        I != E; ++I) {
277     Instruction *Inst = *I;
278
279     for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
280          OI != OE; ++OI)
281       *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
282   }
283
284   return false;
285 }
286
287
288 // LinkMethodBodies - Link in the method bodies that are defined in the source
289 // module into the DestModule.  This consists basically of copying the method
290 // over and fixing up references to values.
291 //
292 static bool LinkMethodBodies(Module *Dest, const Module *Src,
293                              map<const Value*, Value*> &ValueMap,
294                              string *Err = 0) {
295
296   // Loop over all of the methods in the src module, mapping them over as we go
297   //
298   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
299     const Method *SM = *I;                     // Source Method
300     if (!SM->isExternal()) {                   // No body if method is external
301       Method *DM = cast<Method>(ValueMap[SM]); // Destination method
302
303       // DM not external SM external?
304       if (!DM->isExternal()) {
305         if (Err)
306           *Err = "Method '" + (SM->hasName() ? SM->getName() : string("")) +
307                  "' body multiply defined!";
308         return true;
309       }
310
311       if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
312     }
313   }
314   return false;
315 }
316
317
318
319 // LinkModules - This function links two modules together, with the resulting
320 // left module modified to be the composite of the two input modules.  If an
321 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
322 // the problem.  Upon failure, the Dest module could be in a modified state, and
323 // shouldn't be relied on to be consistent.
324 //
325 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
326   // ValueMap - Mapping of values from what they used to be in Src, to what they
327   // are now in Dest.
328   //
329   map<const Value*, Value*> ValueMap;
330
331   // Insert all of the globals in src into the Dest module... without
332   // initializers
333   if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
334
335   // Update the initializers in the Dest module now that all globals that may
336   // be referenced are in Dest.
337   //
338   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
339
340   // Link the methods together between the two modules, without doing method
341   // bodies... this just adds external method prototypes to the Dest method...
342   // We do this so that when we begin processing method bodies, all of the
343   // global values that may be referenced are available in our ValueMap.
344   //
345   if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
346
347   // Link in the method bodies that are defined in the source module into the
348   // DestModule.  This consists basically of copying the method over and fixing
349   // up references to values.
350   //
351   if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
352
353   return false;
354 }
355
356
357 // MangleTypeName - Implement a consistent name-mangling scheme for
358 //                  a given type.
359 // 
360 string
361 MangleTypeName(const Type* type)
362 {
363   string mangledName;
364   
365   if (type->isPrimitiveType())
366     {
367       const string& longName = type->getDescription();
368       mangledName = string(longName.c_str(), (longName.length() < 2)? 1 : 2);
369     }
370   else if (type->getPrimitiveID() == Type::PointerTyID)
371     {
372       PointerType* ptype = (PointerType*) type;
373       mangledName = string("P_" + MangleTypeName(ptype->getValueType()));
374     }
375   else if (type->getPrimitiveID() == Type::StructTyID)
376     {
377       StructType* stype = (StructType*) type;
378       mangledName = string("S_");
379       for (unsigned i=0; i < stype->getNumContainedTypes(); ++i)
380         mangledName += string(MangleTypeName(stype->getContainedType(i)));
381     }
382   else if (type->getPrimitiveID() == Type::ArrayTyID)
383     {
384       ArrayType* atype = (ArrayType*) type;
385       mangledName = string("A_" +MangleTypeName(atype->getElementType()));
386     }
387   else if (type->getPrimitiveID() == Type::MethodTyID)
388     {
389       MethodType* mtype = (MethodType*) type;
390       mangledName = string("M_") + MangleTypeName(mtype->getReturnType());
391       for (unsigned i=1; i < mtype->getNumContainedTypes(); ++i)
392         mangledName += string(MangleTypeName(mtype->getContainedType(i)));
393     }
394   
395   return mangledName;
396 }
397
398
399 // mangleName - implement a consistent name-mangling scheme for all
400 // externally visible (i.e., global) objects.
401 // privateName should be unique within the module.
402 // 
403 string
404 MangleName(const string& privateName, const Value* V)
405 {
406   // Lets drop the P_ before every global name since all globals are ptrs
407   return privateName + "_" +
408     MangleTypeName((isa<GlobalValue>(V)
409                     ? cast<GlobalValue>(V)->getType()->getValueType()
410                     : V->getType()));
411 }