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