Implement Linker/2003-08-23-GlobalVarLinking.ll, which should fix 176.gcc
[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 functions between two modules
9 //
10 //===----------------------------------------------------------------------===//
11
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"
18
19 // Error - Simple wrapper function to conditionally assign to E and return true.
20 // This just makes error return conditions a little bit simpler...
21 //
22 static inline bool Error(std::string *E, const std::string &Message) {
23   if (E) *E = Message;
24   return true;
25 }
26
27 // ResolveTypes - Attempt to link the two specified types together.  Return true
28 // if there is an error and they cannot yet be linked.
29 //
30 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
31                          SymbolTable *DestST, const std::string &Name) {
32   if (DestTy == SrcTy) return false;       // If already equal, noop
33
34   // Does the type already exist in the module?
35   if (DestTy && !isa<OpaqueType>(DestTy)) {  // Yup, the type already exists...
36     if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
37       const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
38     } else {
39       return true;  // Cannot link types... neither is opaque and not-equal
40     }
41   } else {                       // Type not in dest module.  Add it now.
42     if (DestTy)                  // Type _is_ in module, just opaque...
43       const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
44                            ->refineAbstractTypeTo(SrcTy);
45     else if (!Name.empty())
46       DestST->insert(Name, const_cast<Type*>(SrcTy));
47   }
48   return false;
49 }
50
51 static const FunctionType *getFT(const PATypeHolder &TH) {
52   return cast<FunctionType>(TH.get());
53 }
54 static const StructType *getST(const PATypeHolder &TH) {
55   return cast<StructType>(TH.get());
56 }
57
58 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
59 // recurses down into derived types, merging the used types if the parent types
60 // are compatible.
61 //
62 static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
63                                   const PATypeHolder &SrcTy,
64                                   SymbolTable *DestST, const std::string &Name){
65   const Type *SrcTyT = SrcTy.get();
66   const Type *DestTyT = DestTy.get();
67   if (DestTyT == SrcTyT) return false;       // If already equal, noop
68   
69   // If we found our opaque type, resolve it now!
70   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
71     return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
72   
73   // Two types cannot be resolved together if they are of different primitive
74   // type.  For example, we cannot resolve an int to a float.
75   if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
76
77   // Otherwise, resolve the used type used by this derived type...
78   switch (DestTyT->getPrimitiveID()) {
79   case Type::FunctionTyID: {
80     if (cast<FunctionType>(DestTyT)->isVarArg() !=
81         cast<FunctionType>(SrcTyT)->isVarArg())
82       return true;
83     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
84       if (RecursiveResolveTypes(getFT(DestTy)->getContainedType(i),
85                                 getFT(SrcTy)->getContainedType(i), DestST, ""))
86         return true;
87     return false;
88   }
89   case Type::StructTyID: {
90     if (getST(DestTy)->getNumContainedTypes() != 
91         getST(SrcTy)->getNumContainedTypes()) return 1;
92     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
93       if (RecursiveResolveTypes(getST(DestTy)->getContainedType(i),
94                                 getST(SrcTy)->getContainedType(i), DestST, ""))
95         return true;
96     return false;
97   }
98   case Type::ArrayTyID: {
99     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
100     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
101     if (DAT->getNumElements() != SAT->getNumElements()) return true;
102     return RecursiveResolveTypes(DAT->getElementType(), SAT->getElementType(),
103                                  DestST, "");
104   }
105   case Type::PointerTyID:
106     return RecursiveResolveTypes(
107                               cast<PointerType>(DestTy.get())->getElementType(),
108                               cast<PointerType>(SrcTy.get())->getElementType(),
109                                  DestST, "");
110   default: assert(0 && "Unexpected type!"); return true;
111   }  
112 }
113
114
115 // LinkTypes - Go through the symbol table of the Src module and see if any
116 // types are named in the src module that are not named in the Dst module.
117 // Make sure there are no type name conflicts.
118 //
119 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
120   SymbolTable       *DestST = &Dest->getSymbolTable();
121   const SymbolTable *SrcST  = &Src->getSymbolTable();
122
123   // Look for a type plane for Type's...
124   SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
125   if (PI == SrcST->end()) return false;  // No named types, do nothing.
126
127   // Some types cannot be resolved immediately becuse they depend on other types
128   // being resolved to each other first.  This contains a list of types we are
129   // waiting to recheck.
130   std::vector<std::string> DelayedTypesToResolve;
131
132   const SymbolTable::VarMap &VM = PI->second;
133   for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
134        I != E; ++I) {
135     const std::string &Name = I->first;
136     Type *RHS = cast<Type>(I->second);
137
138     // Check to see if this type name is already in the dest module...
139     Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
140
141     if (ResolveTypes(Entry, RHS, DestST, Name)) {
142       // They look different, save the types 'till later to resolve.
143       DelayedTypesToResolve.push_back(Name);
144     }
145   }
146
147   // Iteratively resolve types while we can...
148   while (!DelayedTypesToResolve.empty()) {
149     // Loop over all of the types, attempting to resolve them if possible...
150     unsigned OldSize = DelayedTypesToResolve.size();
151
152     // Try direct resolution by name...
153     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
154       const std::string &Name = DelayedTypesToResolve[i];
155       Type *T1 = cast<Type>(VM.find(Name)->second);
156       Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
157       if (!ResolveTypes(T2, T1, DestST, Name)) {
158         // We are making progress!
159         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
160         --i;
161       }
162     }
163
164     // Did we not eliminate any types?
165     if (DelayedTypesToResolve.size() == OldSize) {
166       // Attempt to resolve subelements of types.  This allows us to merge these
167       // two types: { int* } and { opaque* }
168       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
169         const std::string &Name = DelayedTypesToResolve[i];
170         PATypeHolder T1(cast<Type>(VM.find(Name)->second));
171         PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
172
173         if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
174           // We are making progress!
175           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
176           
177           // Go back to the main loop, perhaps we can resolve directly by name
178           // now...
179           break;
180         }
181       }
182
183       // If we STILL cannot resolve the types, then there is something wrong.
184       // Report the error.
185       if (DelayedTypesToResolve.size() == OldSize) {
186         // Build up an error message of all of the mismatched types.
187         std::string ErrorMessage;
188         for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
189           const std::string &Name = DelayedTypesToResolve[i];
190           const Type *T1 = cast<Type>(VM.find(Name)->second);
191           const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
192           ErrorMessage += "  Type named '" + Name + 
193                           "' conflicts.\n    Src='" + T1->getDescription() +
194                           "'.\n   Dest='" + T2->getDescription() + "'\n";
195         }
196         return Error(Err, "Type conflict between types in modules:\n" +
197                      ErrorMessage);
198       }
199     }
200   }
201
202
203   return false;
204 }
205
206 static void PrintMap(const std::map<const Value*, Value*> &M) {
207   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
208        I != E; ++I) {
209     std::cerr << " Fr: " << (void*)I->first << " ";
210     I->first->dump();
211     std::cerr << " To: " << (void*)I->second << " ";
212     I->second->dump();
213     std::cerr << "\n";
214   }
215 }
216
217
218 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
219 // module to another.  This is somewhat sophisticated in that it can
220 // automatically handle constant references correctly as well...
221 //
222 static Value *RemapOperand(const Value *In,
223                            std::map<const Value*, Value*> &LocalMap,
224                            std::map<const Value*, Value*> *GlobalMap) {
225   std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
226   if (I != LocalMap.end()) return I->second;
227
228   if (GlobalMap) {
229     I = GlobalMap->find(In);
230     if (I != GlobalMap->end()) return I->second;
231   }
232
233   // Check to see if it's a constant that we are interesting in transforming...
234   if (const Constant *CPV = dyn_cast<Constant>(In)) {
235     if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
236       return const_cast<Constant*>(CPV);   // Simple constants stay identical...
237
238     Constant *Result = 0;
239
240     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
241       const std::vector<Use> &Ops = CPA->getValues();
242       std::vector<Constant*> Operands(Ops.size());
243       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
244         Operands[i] = 
245           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
246       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
247     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
248       const std::vector<Use> &Ops = CPS->getValues();
249       std::vector<Constant*> Operands(Ops.size());
250       for (unsigned i = 0; i < Ops.size(); ++i)
251         Operands[i] = 
252           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
253       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
254     } else if (isa<ConstantPointerNull>(CPV)) {
255       Result = const_cast<Constant*>(CPV);
256     } else if (const ConstantPointerRef *CPR =
257                       dyn_cast<ConstantPointerRef>(CPV)) {
258       Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
259       Result = ConstantPointerRef::get(cast<GlobalValue>(V));
260     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
261       if (CE->getOpcode() == Instruction::GetElementPtr) {
262         Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
263         std::vector<Constant*> Indices;
264         Indices.reserve(CE->getNumOperands()-1);
265         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
266           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
267                                                         LocalMap, GlobalMap)));
268
269         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
270       } else if (CE->getNumOperands() == 1) {
271         // Cast instruction
272         assert(CE->getOpcode() == Instruction::Cast);
273         Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
274         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
275       } else if (CE->getNumOperands() == 2) {
276         // Binary operator...
277         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
278         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
279
280         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
281                                    cast<Constant>(V2));        
282       } else {
283         assert(0 && "Unknown constant expr type!");
284       }
285
286     } else {
287       assert(0 && "Unknown type of derived type constant value!");
288     }
289
290     // Cache the mapping in our local map structure...
291     if (GlobalMap)
292       GlobalMap->insert(std::make_pair(In, Result));
293     else
294       LocalMap.insert(std::make_pair(In, Result));
295     return Result;
296   }
297
298   std::cerr << "XXX LocalMap: \n";
299   PrintMap(LocalMap);
300
301   if (GlobalMap) {
302     std::cerr << "XXX GlobalMap: \n";
303     PrintMap(*GlobalMap);
304   }
305
306   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
307   assert(0 && "Couldn't remap value!");
308   return 0;
309 }
310
311 /// FindGlobalNamed - Look in the specified symbol table for a global with the
312 /// specified name and type.  If an exactly matching global does not exist, see
313 /// if there is a global which is "type compatible" with the specified
314 /// name/type.  This allows us to resolve things like '%x = global int*' with
315 /// '%x = global opaque*'.
316 ///
317 static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
318                                     SymbolTable *ST) {
319   // See if an exact match exists in the symbol table...
320   if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
321   
322   // It doesn't exist exactly, scan through all of the type planes in the symbol
323   // table, checking each of them for a type-compatible version.
324   //
325   for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I) {
326     SymbolTable::VarMap &VM = I->second;
327     // Does this type plane contain an entry with the specified name?
328     SymbolTable::type_iterator TI = VM.find(Name);
329     if (TI != VM.end()) {
330       // Determine whether we can fold the two types together, resolving them.
331       // If so, we can use this value.
332       if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
333         return cast<GlobalValue>(TI->second);
334     }
335   }
336   return 0;  // Otherwise, nothing could be found.
337 }
338
339
340 // LinkGlobals - Loop through the global variables in the src module and merge
341 // them into the dest module.
342 //
343 static bool LinkGlobals(Module *Dest, const Module *Src,
344                         std::map<const Value*, Value*> &ValueMap,
345                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
346                         std::string *Err) {
347   // We will need a module level symbol table if the src module has a module
348   // level symbol table...
349   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
350   
351   // Loop over all of the globals in the src module, mapping them over as we go
352   //
353   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
354     const GlobalVariable *SGV = I;
355     GlobalVariable *DGV = 0;
356     if (SGV->hasName()) {
357       // A same named thing is a global variable, because the only two things
358       // that may be in a module level symbol table are Global Vars and
359       // Functions, and they both have distinct, nonoverlapping, possible types.
360       // 
361       DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(), 
362                                                          SGV->getType(), ST));
363     }
364
365     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
366            "Global must either be external or have an initializer!");
367
368     bool SGExtern = SGV->isExternal();
369     bool DGExtern = DGV ? DGV->isExternal() : false;
370
371     if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
372       // No linking to be performed, simply create an identical version of the
373       // symbol over in the dest module... the initializer will be filled in
374       // later by LinkGlobalInits...
375       //
376       GlobalVariable *NewDGV =
377         new GlobalVariable(SGV->getType()->getElementType(),
378                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
379                            SGV->getName(), Dest);
380
381       // If the LLVM runtime renamed the global, but it is an externally visible
382       // symbol, DGV must be an existing global with internal linkage.  Rename
383       // it.
384       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
385         assert(DGV && DGV->getName() == SGV->getName() &&
386                DGV->hasInternalLinkage());
387         DGV->setName("");
388         NewDGV->setName(SGV->getName());  // Force the name back
389         DGV->setName(SGV->getName());     // This will cause a renaming
390         assert(NewDGV->getName() == SGV->getName() &&
391                DGV->getName() != SGV->getName());
392       }
393
394       // Make sure to remember this mapping...
395       ValueMap.insert(std::make_pair(SGV, NewDGV));
396       if (SGV->hasAppendingLinkage())
397         // Keep track that this is an appending variable...
398         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
399
400     } else if (SGV->isExternal()) {
401       // If SGV is external or if both SGV & DGV are external..  Just link the
402       // external globals, we aren't adding anything.
403       ValueMap.insert(std::make_pair(SGV, DGV));
404
405     } else if (DGV->isExternal()) {   // If DGV is external but SGV is not...
406       ValueMap.insert(std::make_pair(SGV, DGV));
407       DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
408     } else if (SGV->getLinkage() != DGV->getLinkage()) {
409       return Error(Err, "Global variables named '" + SGV->getName() +
410                    "' have different linkage specifiers!");
411     } else if (SGV->hasExternalLinkage()) {
412       // Allow linking two exactly identical external global variables...
413       if (SGV->isConstant() != DGV->isConstant() ||
414           SGV->getInitializer() != DGV->getInitializer())
415         return Error(Err, "Global Variable Collision on '" + 
416                      SGV->getType()->getDescription() + " %" + SGV->getName() +
417                      "' - Global variables differ in const'ness");
418       ValueMap.insert(std::make_pair(SGV, DGV));
419     } else if (SGV->hasLinkOnceLinkage()) {
420       // If the global variable has a name, and that name is already in use in
421       // the Dest module, make sure that the name is a compatible global
422       // variable...
423       //
424       // Check to see if the two GV's have the same Const'ness...
425       if (SGV->isConstant() != DGV->isConstant())
426         return Error(Err, "Global Variable Collision on '" + 
427                      SGV->getType()->getDescription() + " %" + SGV->getName() +
428                      "' - Global variables differ in const'ness");
429
430       // Okay, everything is cool, remember the mapping...
431       ValueMap.insert(std::make_pair(SGV, DGV));
432     } else if (SGV->hasAppendingLinkage()) {
433       // No linking is performed yet.  Just insert a new copy of the global, and
434       // keep track of the fact that it is an appending variable in the
435       // AppendingVars map.  The name is cleared out so that no linkage is
436       // performed.
437       GlobalVariable *NewDGV =
438         new GlobalVariable(SGV->getType()->getElementType(),
439                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
440                            "", Dest);
441
442       // Make sure to remember this mapping...
443       ValueMap.insert(std::make_pair(SGV, NewDGV));
444
445       // Keep track that this is an appending variable...
446       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
447     } else {
448       assert(0 && "Unknown linkage!");
449     }
450   }
451   return false;
452 }
453
454
455 // LinkGlobalInits - Update the initializers in the Dest module now that all
456 // globals that may be referenced are in Dest.
457 //
458 static bool LinkGlobalInits(Module *Dest, const Module *Src,
459                             std::map<const Value*, Value*> &ValueMap,
460                             std::string *Err) {
461
462   // Loop over all of the globals in the src module, mapping them over as we go
463   //
464   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
465     const GlobalVariable *SGV = I;
466
467     if (SGV->hasInitializer()) {      // Only process initialized GV's
468       // Figure out what the initializer looks like in the dest module...
469       Constant *SInit =
470         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
471
472       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
473       if (DGV->hasInitializer()) {
474         assert(SGV->getLinkage() == DGV->getLinkage());
475         if (SGV->hasExternalLinkage()) {
476           if (DGV->getInitializer() != SInit)
477             return Error(Err, "Global Variable Collision on '" + 
478                          SGV->getType()->getDescription() +"':%"+SGV->getName()+
479                          " - Global variables have different initializers");
480         } else if (DGV->hasLinkOnceLinkage()) {
481           // Nothing is required, mapped values will take the new global
482           // automatically.
483         } else if (DGV->hasAppendingLinkage()) {
484           assert(0 && "Appending linkage unimplemented!");
485         } else {
486           assert(0 && "Unknown linkage!");
487         }
488       } else {
489         // Copy the initializer over now...
490         DGV->setInitializer(SInit);
491       }
492     }
493   }
494   return false;
495 }
496
497 // LinkFunctionProtos - Link the functions together between the two modules,
498 // without doing function bodies... this just adds external function prototypes
499 // to the Dest function...
500 //
501 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
502                                std::map<const Value*, Value*> &ValueMap,
503                                std::string *Err) {
504   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
505   
506   // Loop over all of the functions in the src module, mapping them over as we
507   // go
508   //
509   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
510     const Function *SF = I;   // SrcFunction
511     Function *DF = 0;
512     if (SF->hasName())
513       // The same named thing is a Function, because the only two things
514       // that may be in a module level symbol table are Global Vars and
515       // Functions, and they both have distinct, nonoverlapping, possible types.
516       // 
517       DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
518                                                   ST));
519
520     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
521       // Function does not already exist, simply insert an function signature
522       // identical to SF into the dest module...
523       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
524                                      SF->getName(), Dest);
525
526       // If the LLVM runtime renamed the function, but it is an externally
527       // visible symbol, DF must be an existing function with internal linkage.
528       // Rename it.
529       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
530         assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
531         DF->setName("");
532         NewDF->setName(SF->getName());  // Force the name back
533         DF->setName(SF->getName());     // This will cause a renaming
534         assert(NewDF->getName() == SF->getName() &&
535                DF->getName() != SF->getName());
536       }
537
538       // ... and remember this mapping...
539       ValueMap.insert(std::make_pair(SF, NewDF));
540     } else if (SF->isExternal()) {
541       // If SF is external or if both SF & DF are external..  Just link the
542       // external functions, we aren't adding anything.
543       ValueMap.insert(std::make_pair(SF, DF));
544     } else if (DF->isExternal()) {   // If DF is external but SF is not...
545       // Link the external functions, update linkage qualifiers
546       ValueMap.insert(std::make_pair(SF, DF));
547       DF->setLinkage(SF->getLinkage());
548
549     } else if (SF->getLinkage() != DF->getLinkage()) {
550       return Error(Err, "Functions named '" + SF->getName() +
551                    "' have different linkage specifiers!");
552     } else if (SF->hasExternalLinkage()) {
553       // The function is defined in both modules!!
554       return Error(Err, "Function '" + 
555                    SF->getFunctionType()->getDescription() + "':\"" + 
556                    SF->getName() + "\" - Function is already defined!");
557     } else if (SF->hasLinkOnceLinkage()) {
558       // Completely ignore the source function.
559       ValueMap.insert(std::make_pair(SF, DF));
560     } else {
561       assert(0 && "Unknown linkage configuration found!");
562     }
563   }
564   return false;
565 }
566
567 // LinkFunctionBody - Copy the source function over into the dest function and
568 // fix up references to values.  At this point we know that Dest is an external
569 // function, and that Src is not.
570 //
571 static bool LinkFunctionBody(Function *Dest, const Function *Src,
572                              std::map<const Value*, Value*> &GlobalMap,
573                              std::string *Err) {
574   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
575   std::map<const Value*, Value*> LocalMap;   // Map for function local values
576
577   // Go through and convert function arguments over...
578   Function::aiterator DI = Dest->abegin();
579   for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
580        I != E; ++I, ++DI) {
581     DI->setName(I->getName());  // Copy the name information over...
582
583     // Add a mapping to our local map
584     LocalMap.insert(std::make_pair(I, DI));
585   }
586
587   // Loop over all of the basic blocks, copying the instructions over...
588   //
589   for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
590     // Create new basic block and add to mapping and the Dest function...
591     BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
592     LocalMap.insert(std::make_pair(I, DBB));
593
594     // Loop over all of the instructions in the src basic block, copying them
595     // over.  Note that this is broken in a strict sense because the cloned
596     // instructions will still be referencing values in the Src module, not
597     // the remapped values.  In our case, however, we will not get caught and 
598     // so we can delay patching the values up until later...
599     //
600     for (BasicBlock::const_iterator II = I->begin(), IE = I->end(); 
601          II != IE; ++II) {
602       Instruction *DI = II->clone();
603       DI->setName(II->getName());
604       DBB->getInstList().push_back(DI);
605       LocalMap.insert(std::make_pair(II, DI));
606     }
607   }
608
609   // At this point, all of the instructions and values of the function are now
610   // copied over.  The only problem is that they are still referencing values in
611   // the Source function as operands.  Loop through all of the operands of the
612   // functions and patch them up to point to the local versions...
613   //
614   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
615     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
616       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
617            OI != OE; ++OI)
618         *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
619
620   return false;
621 }
622
623
624 // LinkFunctionBodies - Link in the function bodies that are defined in the
625 // source module into the DestModule.  This consists basically of copying the
626 // function over and fixing up references to values.
627 //
628 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
629                                std::map<const Value*, Value*> &ValueMap,
630                                std::string *Err) {
631
632   // Loop over all of the functions in the src module, mapping them over as we
633   // go
634   //
635   for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
636     if (!SF->isExternal()) {                  // No body if function is external
637       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
638
639       // DF not external SF external?
640       if (!DF->isExternal()) {
641         if (DF->hasLinkOnceLinkage()) continue; // No relinkage for link-once!
642         if (Err)
643           *Err = "Function '" + (SF->hasName() ? SF->getName() :std::string(""))
644                + "' body multiply defined!";
645         return true;
646       }
647
648       if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
649     }
650   }
651   return false;
652 }
653
654 // LinkAppendingVars - If there were any appending global variables, link them
655 // together now.  Return true on error.
656 //
657 static bool LinkAppendingVars(Module *M,
658                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
659                               std::string *ErrorMsg) {
660   if (AppendingVars.empty()) return false; // Nothing to do.
661   
662   // Loop over the multimap of appending vars, processing any variables with the
663   // same name, forming a new appending global variable with both of the
664   // initializers merged together, then rewrite references to the old variables
665   // and delete them.
666   //
667   std::vector<Constant*> Inits;
668   while (AppendingVars.size() > 1) {
669     // Get the first two elements in the map...
670     std::multimap<std::string,
671       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
672
673     // If the first two elements are for different names, there is no pair...
674     // Otherwise there is a pair, so link them together...
675     if (First->first == Second->first) {
676       GlobalVariable *G1 = First->second, *G2 = Second->second;
677       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
678       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
679       
680       // Check to see that they two arrays agree on type...
681       if (T1->getElementType() != T2->getElementType())
682         return Error(ErrorMsg,
683          "Appending variables with different element types need to be linked!");
684       if (G1->isConstant() != G2->isConstant())
685         return Error(ErrorMsg,
686                      "Appending variables linked with different const'ness!");
687
688       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
689       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
690
691       // Create the new global variable...
692       GlobalVariable *NG =
693         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
694                            /*init*/0, First->first, M);
695
696       // Merge the initializer...
697       Inits.reserve(NewSize);
698       ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
699       for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
700         Inits.push_back(cast<Constant>(I->getValues()[i]));
701       I = cast<ConstantArray>(G2->getInitializer());
702       for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
703         Inits.push_back(cast<Constant>(I->getValues()[i]));
704       NG->setInitializer(ConstantArray::get(NewType, Inits));
705       Inits.clear();
706
707       // Replace any uses of the two global variables with uses of the new
708       // global...
709
710       // FIXME: This should rewrite simple/straight-forward uses such as
711       // getelementptr instructions to not use the Cast!
712       ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
713       G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
714       G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
715
716       // Remove the two globals from the module now...
717       M->getGlobalList().erase(G1);
718       M->getGlobalList().erase(G2);
719
720       // Put the new global into the AppendingVars map so that we can handle
721       // linking of more than two vars...
722       Second->second = NG;
723     }
724     AppendingVars.erase(First);
725   }
726
727   return false;
728 }
729
730
731 // LinkModules - This function links two modules together, with the resulting
732 // left module modified to be the composite of the two input modules.  If an
733 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
734 // the problem.  Upon failure, the Dest module could be in a modified state, and
735 // shouldn't be relied on to be consistent.
736 //
737 bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
738   if (Dest->getEndianness() != Src->getEndianness())
739     std::cerr << "WARNING: Linking two modules of different endianness!\n";
740   if (Dest->getPointerSize() != Src->getPointerSize())
741     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
742
743   // LinkTypes - Go through the symbol table of the Src module and see if any
744   // types are named in the src module that are not named in the Dst module.
745   // Make sure there are no type name conflicts.
746   //
747   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
748
749   // ValueMap - Mapping of values from what they used to be in Src, to what they
750   // are now in Dest.
751   //
752   std::map<const Value*, Value*> ValueMap;
753
754   // AppendingVars - Keep track of global variables in the destination module
755   // with appending linkage.  After the module is linked together, they are
756   // appended and the module is rewritten.
757   //
758   std::multimap<std::string, GlobalVariable *> AppendingVars;
759
760   // Add all of the appending globals already in the Dest module to
761   // AppendingVars.
762   for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
763     if (I->hasAppendingLinkage())
764       AppendingVars.insert(std::make_pair(I->getName(), I));
765
766   // Insert all of the globals in src into the Dest module... without linking
767   // initializers (which could refer to functions not yet mapped over).
768   //
769   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
770
771   // Link the functions together between the two modules, without doing function
772   // bodies... this just adds external function prototypes to the Dest
773   // function...  We do this so that when we begin processing function bodies,
774   // all of the global values that may be referenced are available in our
775   // ValueMap.
776   //
777   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
778
779   // Update the initializers in the Dest module now that all globals that may
780   // be referenced are in Dest.
781   //
782   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
783
784   // Link in the function bodies that are defined in the source module into the
785   // DestModule.  This consists basically of copying the function over and
786   // fixing up references to values.
787   //
788   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
789
790   // If there were any appending global variables, link them together now.
791   //
792   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
793
794   return false;
795 }
796