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