Reversed the order of the llvm.writeport() operands so that the value
[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/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Assembly/Writer.h"
26 using 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='";
243         WriteTypeSymbolic(std::cerr, T1, Src);
244         std::cerr << "'.\n   Dest='";
245         WriteTypeSymbolic(std::cerr, T2, Dest);
246         std::cerr << "'\n";
247
248         // Remove the symbol name from the destination.
249         DelayedTypesToResolve.pop_back();
250       }
251     }
252   }
253
254
255   return false;
256 }
257
258 static void PrintMap(const std::map<const Value*, Value*> &M) {
259   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
260        I != E; ++I) {
261     std::cerr << " Fr: " << (void*)I->first << " ";
262     I->first->dump();
263     std::cerr << " To: " << (void*)I->second << " ";
264     I->second->dump();
265     std::cerr << "\n";
266   }
267 }
268
269
270 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
271 // module to another.  This is somewhat sophisticated in that it can
272 // automatically handle constant references correctly as well...
273 //
274 static Value *RemapOperand(const Value *In,
275                            std::map<const Value*, Value*> &LocalMap,
276                            std::map<const Value*, Value*> *GlobalMap) {
277   std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
278   if (I != LocalMap.end()) return I->second;
279
280   if (GlobalMap) {
281     I = GlobalMap->find(In);
282     if (I != GlobalMap->end()) return I->second;
283   }
284
285   // Check to see if it's a constant that we are interesting in transforming...
286   if (const Constant *CPV = dyn_cast<Constant>(In)) {
287     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
288         isa<ConstantAggregateZero>(CPV))
289       return const_cast<Constant*>(CPV);   // Simple constants stay identical...
290
291     Constant *Result = 0;
292
293     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
294       const std::vector<Use> &Ops = CPA->getValues();
295       std::vector<Constant*> Operands(Ops.size());
296       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
297         Operands[i] = 
298           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
299       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
300     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
301       const std::vector<Use> &Ops = CPS->getValues();
302       std::vector<Constant*> Operands(Ops.size());
303       for (unsigned i = 0; i < Ops.size(); ++i)
304         Operands[i] = 
305           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
306       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
307     } else if (isa<ConstantPointerNull>(CPV)) {
308       Result = const_cast<Constant*>(CPV);
309     } else if (const ConstantPointerRef *CPR =
310                       dyn_cast<ConstantPointerRef>(CPV)) {
311       Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
312       Result = ConstantPointerRef::get(cast<GlobalValue>(V));
313     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
314       if (CE->getOpcode() == Instruction::GetElementPtr) {
315         Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
316         std::vector<Constant*> Indices;
317         Indices.reserve(CE->getNumOperands()-1);
318         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
319           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
320                                                         LocalMap, GlobalMap)));
321
322         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
323       } else if (CE->getNumOperands() == 1) {
324         // Cast instruction
325         assert(CE->getOpcode() == Instruction::Cast);
326         Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
327         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
328       } else if (CE->getNumOperands() == 3) {
329         // Select instruction
330         assert(CE->getOpcode() == Instruction::Select);
331         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
332         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
333         Value *V3 = RemapOperand(CE->getOperand(2), LocalMap, GlobalMap);
334         Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
335                                          cast<Constant>(V3));
336       } else if (CE->getNumOperands() == 2) {
337         // Binary operator...
338         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
339         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
340
341         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
342                                    cast<Constant>(V2));
343       } else {
344         assert(0 && "Unknown constant expr type!");
345       }
346
347     } else {
348       assert(0 && "Unknown type of derived type constant value!");
349     }
350
351     // Cache the mapping in our local map structure...
352     if (GlobalMap)
353       GlobalMap->insert(std::make_pair(In, Result));
354     else
355       LocalMap.insert(std::make_pair(In, Result));
356     return Result;
357   }
358
359   std::cerr << "XXX LocalMap: \n";
360   PrintMap(LocalMap);
361
362   if (GlobalMap) {
363     std::cerr << "XXX GlobalMap: \n";
364     PrintMap(*GlobalMap);
365   }
366
367   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
368   assert(0 && "Couldn't remap value!");
369   return 0;
370 }
371
372 /// FindGlobalNamed - Look in the specified symbol table for a global with the
373 /// specified name and type.  If an exactly matching global does not exist, see
374 /// if there is a global which is "type compatible" with the specified
375 /// name/type.  This allows us to resolve things like '%x = global int*' with
376 /// '%x = global opaque*'.
377 ///
378 static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
379                                     SymbolTable *ST) {
380   // See if an exact match exists in the symbol table...
381   if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
382   
383   // It doesn't exist exactly, scan through all of the type planes in the symbol
384   // table, checking each of them for a type-compatible version.
385   //
386   for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
387     if (I->first != Type::TypeTy) {
388       SymbolTable::VarMap &VM = I->second;
389
390       // Does this type plane contain an entry with the specified name?
391       SymbolTable::type_iterator TI = VM.find(Name);
392       if (TI != VM.end()) {
393         //
394         // Ensure that this type if placed correctly into the symbol table.
395         //
396         assert(TI->second->getType() == I->first && "Type conflict!");
397
398         //
399         // Save a reference to the new type.  Resolving the type can modify the
400         // symbol table, invalidating the TI variable.
401         //
402         Value *ValPtr = TI->second;
403
404         //
405         // Determine whether we can fold the two types together, resolving them.
406         // If so, we can use this value.
407         //
408         if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
409           return cast<GlobalValue>(ValPtr);
410       }
411     }
412   return 0;  // Otherwise, nothing could be found.
413 }
414
415
416 // LinkGlobals - Loop through the global variables in the src module and merge
417 // them into the dest module.
418 //
419 static bool LinkGlobals(Module *Dest, const Module *Src,
420                         std::map<const Value*, Value*> &ValueMap,
421                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
422                         std::string *Err) {
423   // We will need a module level symbol table if the src module has a module
424   // level symbol table...
425   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
426   
427   // Loop over all of the globals in the src module, mapping them over as we go
428   //
429   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
430     const GlobalVariable *SGV = I;
431     GlobalVariable *DGV = 0;
432     if (SGV->hasName()) {
433       // A same named thing is a global variable, because the only two things
434       // that may be in a module level symbol table are Global Vars and
435       // Functions, and they both have distinct, nonoverlapping, possible types.
436       // 
437       DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(), 
438                                                          SGV->getType(), ST));
439     }
440
441     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
442            "Global must either be external or have an initializer!");
443
444     bool SGExtern = SGV->isExternal();
445     bool DGExtern = DGV ? DGV->isExternal() : false;
446
447     if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
448       // No linking to be performed, simply create an identical version of the
449       // symbol over in the dest module... the initializer will be filled in
450       // later by LinkGlobalInits...
451       //
452       GlobalVariable *NewDGV =
453         new GlobalVariable(SGV->getType()->getElementType(),
454                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
455                            SGV->getName(), Dest);
456
457       // If the LLVM runtime renamed the global, but it is an externally visible
458       // symbol, DGV must be an existing global with internal linkage.  Rename
459       // it.
460       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
461         assert(DGV && DGV->getName() == SGV->getName() &&
462                DGV->hasInternalLinkage());
463         DGV->setName("");
464         NewDGV->setName(SGV->getName());  // Force the name back
465         DGV->setName(SGV->getName());     // This will cause a renaming
466         assert(NewDGV->getName() == SGV->getName() &&
467                DGV->getName() != SGV->getName());
468       }
469
470       // Make sure to remember this mapping...
471       ValueMap.insert(std::make_pair(SGV, NewDGV));
472       if (SGV->hasAppendingLinkage())
473         // Keep track that this is an appending variable...
474         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
475
476     } else if (SGV->isExternal()) {
477       // If SGV is external or if both SGV & DGV are external..  Just link the
478       // external globals, we aren't adding anything.
479       ValueMap.insert(std::make_pair(SGV, DGV));
480
481     } else if (DGV->isExternal()) {   // If DGV is external but SGV is not...
482       ValueMap.insert(std::make_pair(SGV, DGV));
483       DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
484     } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
485       // At this point we know that DGV has LinkOnce, Appending, Weak, or
486       // External linkage.  If DGV is Appending, this is an error.
487       if (DGV->hasAppendingLinkage())
488         return Error(Err, "Linking globals named '" + SGV->getName() +
489                      " ' with 'weak' and 'appending' linkage is not allowed!");
490
491       if (SGV->isConstant() != DGV->isConstant())
492         return Error(Err, "Global Variable Collision on '" + 
493                      SGV->getType()->getDescription() + " %" + SGV->getName() +
494                      "' - Global variables differ in const'ness");
495
496       // Otherwise, just perform the link.
497       ValueMap.insert(std::make_pair(SGV, DGV));
498
499       // Linkonce+Weak = Weak
500       if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
501         DGV->setLinkage(SGV->getLinkage());
502
503     } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
504       // At this point we know that SGV has LinkOnce, Appending, or External
505       // linkage.  If SGV is Appending, this is an error.
506       if (SGV->hasAppendingLinkage())
507         return Error(Err, "Linking globals named '" + SGV->getName() +
508                      " ' with 'weak' and 'appending' linkage is not allowed!");
509
510       if (SGV->isConstant() != DGV->isConstant())
511         return Error(Err, "Global Variable Collision on '" + 
512                      SGV->getType()->getDescription() + " %" + SGV->getName() +
513                      "' - Global variables differ in const'ness");
514
515       if (!SGV->hasLinkOnceLinkage())
516         DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
517       ValueMap.insert(std::make_pair(SGV, DGV));
518   
519     } else if (SGV->getLinkage() != DGV->getLinkage()) {
520       return Error(Err, "Global variables named '" + SGV->getName() +
521                    "' have different linkage specifiers!");
522     } else if (SGV->hasExternalLinkage()) {
523       // Allow linking two exactly identical external global variables...
524       if (SGV->isConstant() != DGV->isConstant())
525         return Error(Err, "Global Variable Collision on '" + 
526                      SGV->getType()->getDescription() + " %" + SGV->getName() +
527                      "' - Global variables differ in const'ness");
528
529       if (SGV->getInitializer() != DGV->getInitializer())
530         return Error(Err, "Global Variable Collision on '" + 
531                      SGV->getType()->getDescription() + " %" + SGV->getName() +
532                     "' - External linkage globals have different initializers");
533
534       ValueMap.insert(std::make_pair(SGV, DGV));
535     } else if (SGV->hasAppendingLinkage()) {
536       // No linking is performed yet.  Just insert a new copy of the global, and
537       // keep track of the fact that it is an appending variable in the
538       // AppendingVars map.  The name is cleared out so that no linkage is
539       // performed.
540       GlobalVariable *NewDGV =
541         new GlobalVariable(SGV->getType()->getElementType(),
542                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
543                            "", Dest);
544
545       // Make sure to remember this mapping...
546       ValueMap.insert(std::make_pair(SGV, NewDGV));
547
548       // Keep track that this is an appending variable...
549       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
550     } else {
551       assert(0 && "Unknown linkage!");
552     }
553   }
554   return false;
555 }
556
557
558 // LinkGlobalInits - Update the initializers in the Dest module now that all
559 // globals that may be referenced are in Dest.
560 //
561 static bool LinkGlobalInits(Module *Dest, const Module *Src,
562                             std::map<const Value*, Value*> &ValueMap,
563                             std::string *Err) {
564
565   // Loop over all of the globals in the src module, mapping them over as we go
566   //
567   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
568     const GlobalVariable *SGV = I;
569
570     if (SGV->hasInitializer()) {      // Only process initialized GV's
571       // Figure out what the initializer looks like in the dest module...
572       Constant *SInit =
573         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
574
575       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
576       if (DGV->hasInitializer()) {
577         if (SGV->hasExternalLinkage()) {
578           if (DGV->getInitializer() != SInit)
579             return Error(Err, "Global Variable Collision on '" + 
580                          SGV->getType()->getDescription() +"':%"+SGV->getName()+
581                          " - Global variables have different initializers");
582         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
583           // Nothing is required, mapped values will take the new global
584           // automatically.
585         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
586           // Nothing is required, mapped values will take the new global
587           // automatically.
588         } else if (DGV->hasAppendingLinkage()) {
589           assert(0 && "Appending linkage unimplemented!");
590         } else {
591           assert(0 && "Unknown linkage!");
592         }
593       } else {
594         // Copy the initializer over now...
595         DGV->setInitializer(SInit);
596       }
597     }
598   }
599   return false;
600 }
601
602 // LinkFunctionProtos - Link the functions together between the two modules,
603 // without doing function bodies... this just adds external function prototypes
604 // to the Dest function...
605 //
606 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
607                                std::map<const Value*, Value*> &ValueMap,
608                                std::string *Err) {
609   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
610   
611   // Loop over all of the functions in the src module, mapping them over as we
612   // go
613   //
614   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
615     const Function *SF = I;   // SrcFunction
616     Function *DF = 0;
617     if (SF->hasName())
618       // The same named thing is a Function, because the only two things
619       // that may be in a module level symbol table are Global Vars and
620       // Functions, and they both have distinct, nonoverlapping, possible types.
621       // 
622       DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
623                                                   ST));
624
625     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
626       // Function does not already exist, simply insert an function signature
627       // identical to SF into the dest module...
628       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
629                                      SF->getName(), Dest);
630
631       // If the LLVM runtime renamed the function, but it is an externally
632       // visible symbol, DF must be an existing function with internal linkage.
633       // Rename it.
634       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
635         assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
636         DF->setName("");
637         NewDF->setName(SF->getName());  // Force the name back
638         DF->setName(SF->getName());     // This will cause a renaming
639         assert(NewDF->getName() == SF->getName() &&
640                DF->getName() != SF->getName());
641       }
642
643       // ... and remember this mapping...
644       ValueMap.insert(std::make_pair(SF, NewDF));
645     } else if (SF->isExternal()) {
646       // If SF is external or if both SF & DF are external..  Just link the
647       // external functions, we aren't adding anything.
648       ValueMap.insert(std::make_pair(SF, DF));
649     } else if (DF->isExternal()) {   // If DF is external but SF is not...
650       // Link the external functions, update linkage qualifiers
651       ValueMap.insert(std::make_pair(SF, DF));
652       DF->setLinkage(SF->getLinkage());
653
654     } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
655       // At this point we know that DF has LinkOnce, Weak, or External linkage.
656       ValueMap.insert(std::make_pair(SF, DF));
657
658       // Linkonce+Weak = Weak
659       if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
660         DF->setLinkage(SF->getLinkage());
661
662     } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
663       // At this point we know that SF has LinkOnce or External linkage.
664       ValueMap.insert(std::make_pair(SF, DF));
665       if (!SF->hasLinkOnceLinkage())   // Don't inherit linkonce linkage
666         DF->setLinkage(SF->getLinkage());
667
668     } else if (SF->getLinkage() != DF->getLinkage()) {
669       return Error(Err, "Functions named '" + SF->getName() +
670                    "' have different linkage specifiers!");
671     } else if (SF->hasExternalLinkage()) {
672       // The function is defined in both modules!!
673       return Error(Err, "Function '" + 
674                    SF->getFunctionType()->getDescription() + "':\"" + 
675                    SF->getName() + "\" - Function is already defined!");
676     } else {
677       assert(0 && "Unknown linkage configuration found!");
678     }
679   }
680   return false;
681 }
682
683 // LinkFunctionBody - Copy the source function over into the dest function and
684 // fix up references to values.  At this point we know that Dest is an external
685 // function, and that Src is not.
686 //
687 static bool LinkFunctionBody(Function *Dest, const Function *Src,
688                              std::map<const Value*, Value*> &GlobalMap,
689                              std::string *Err) {
690   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
691   std::map<const Value*, Value*> LocalMap;   // Map for function local values
692
693   // Go through and convert function arguments over...
694   Function::aiterator DI = Dest->abegin();
695   for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
696        I != E; ++I, ++DI) {
697     DI->setName(I->getName());  // Copy the name information over...
698
699     // Add a mapping to our local map
700     LocalMap.insert(std::make_pair(I, DI));
701   }
702
703   // Loop over all of the basic blocks, copying the instructions over...
704   //
705   for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
706     // Create new basic block and add to mapping and the Dest function...
707     BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
708     LocalMap.insert(std::make_pair(I, DBB));
709
710     // Loop over all of the instructions in the src basic block, copying them
711     // over.  Note that this is broken in a strict sense because the cloned
712     // instructions will still be referencing values in the Src module, not
713     // the remapped values.  In our case, however, we will not get caught and 
714     // so we can delay patching the values up until later...
715     //
716     for (BasicBlock::const_iterator II = I->begin(), IE = I->end(); 
717          II != IE; ++II) {
718       Instruction *DI = II->clone();
719       DI->setName(II->getName());
720       DBB->getInstList().push_back(DI);
721       LocalMap.insert(std::make_pair(II, DI));
722     }
723   }
724
725   // At this point, all of the instructions and values of the function are now
726   // copied over.  The only problem is that they are still referencing values in
727   // the Source function as operands.  Loop through all of the operands of the
728   // functions and patch them up to point to the local versions...
729   //
730   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
731     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
732       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
733            OI != OE; ++OI)
734         *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
735
736   return false;
737 }
738
739
740 // LinkFunctionBodies - Link in the function bodies that are defined in the
741 // source module into the DestModule.  This consists basically of copying the
742 // function over and fixing up references to values.
743 //
744 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
745                                std::map<const Value*, Value*> &ValueMap,
746                                std::string *Err) {
747
748   // Loop over all of the functions in the src module, mapping them over as we
749   // go
750   //
751   for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
752     if (!SF->isExternal()) {                  // No body if function is external
753       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
754
755       // DF not external SF external?
756       if (DF->isExternal()) {
757         // Only provide the function body if there isn't one already.
758         if (LinkFunctionBody(DF, SF, ValueMap, Err))
759           return true;
760       }
761     }
762   }
763   return false;
764 }
765
766 // LinkAppendingVars - If there were any appending global variables, link them
767 // together now.  Return true on error.
768 //
769 static bool LinkAppendingVars(Module *M,
770                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
771                               std::string *ErrorMsg) {
772   if (AppendingVars.empty()) return false; // Nothing to do.
773   
774   // Loop over the multimap of appending vars, processing any variables with the
775   // same name, forming a new appending global variable with both of the
776   // initializers merged together, then rewrite references to the old variables
777   // and delete them.
778   //
779   std::vector<Constant*> Inits;
780   while (AppendingVars.size() > 1) {
781     // Get the first two elements in the map...
782     std::multimap<std::string,
783       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
784
785     // If the first two elements are for different names, there is no pair...
786     // Otherwise there is a pair, so link them together...
787     if (First->first == Second->first) {
788       GlobalVariable *G1 = First->second, *G2 = Second->second;
789       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
790       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
791       
792       // Check to see that they two arrays agree on type...
793       if (T1->getElementType() != T2->getElementType())
794         return Error(ErrorMsg,
795          "Appending variables with different element types need to be linked!");
796       if (G1->isConstant() != G2->isConstant())
797         return Error(ErrorMsg,
798                      "Appending variables linked with different const'ness!");
799
800       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
801       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
802
803       // Create the new global variable...
804       GlobalVariable *NG =
805         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
806                            /*init*/0, First->first, M);
807
808       // Merge the initializer...
809       Inits.reserve(NewSize);
810       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
811         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
812           Inits.push_back(cast<Constant>(I->getValues()[i]));
813       } else {
814         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
815         Constant *CV = Constant::getNullValue(T1->getElementType());
816         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
817           Inits.push_back(CV);
818       }
819       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
820         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
821           Inits.push_back(cast<Constant>(I->getValues()[i]));
822       } else {
823         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
824         Constant *CV = Constant::getNullValue(T2->getElementType());
825         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
826           Inits.push_back(CV);
827       }
828       NG->setInitializer(ConstantArray::get(NewType, Inits));
829       Inits.clear();
830
831       // Replace any uses of the two global variables with uses of the new
832       // global...
833
834       // FIXME: This should rewrite simple/straight-forward uses such as
835       // getelementptr instructions to not use the Cast!
836       ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
837       G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
838       G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
839
840       // Remove the two globals from the module now...
841       M->getGlobalList().erase(G1);
842       M->getGlobalList().erase(G2);
843
844       // Put the new global into the AppendingVars map so that we can handle
845       // linking of more than two vars...
846       Second->second = NG;
847     }
848     AppendingVars.erase(First);
849   }
850
851   return false;
852 }
853
854
855 // LinkModules - This function links two modules together, with the resulting
856 // left module modified to be the composite of the two input modules.  If an
857 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
858 // the problem.  Upon failure, the Dest module could be in a modified state, and
859 // shouldn't be relied on to be consistent.
860 //
861 bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
862   if (Dest->getEndianness() == Module::AnyEndianness)
863     Dest->setEndianness(Src->getEndianness());
864   if (Dest->getPointerSize() == Module::AnyPointerSize)
865     Dest->setPointerSize(Src->getPointerSize());
866
867   if (Src->getEndianness() != Module::AnyEndianness &&
868       Dest->getEndianness() != Src->getEndianness())
869     std::cerr << "WARNING: Linking two modules of different endianness!\n";
870   if (Src->getPointerSize() != Module::AnyPointerSize &&
871       Dest->getPointerSize() != Src->getPointerSize())
872     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
873
874   // LinkTypes - Go through the symbol table of the Src module and see if any
875   // types are named in the src module that are not named in the Dst module.
876   // Make sure there are no type name conflicts.
877   //
878   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
879
880   // ValueMap - Mapping of values from what they used to be in Src, to what they
881   // are now in Dest.
882   //
883   std::map<const Value*, Value*> ValueMap;
884
885   // AppendingVars - Keep track of global variables in the destination module
886   // with appending linkage.  After the module is linked together, they are
887   // appended and the module is rewritten.
888   //
889   std::multimap<std::string, GlobalVariable *> AppendingVars;
890
891   // Add all of the appending globals already in the Dest module to
892   // AppendingVars.
893   for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
894     if (I->hasAppendingLinkage())
895       AppendingVars.insert(std::make_pair(I->getName(), I));
896
897   // Insert all of the globals in src into the Dest module... without linking
898   // initializers (which could refer to functions not yet mapped over).
899   //
900   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
901
902   // Link the functions together between the two modules, without doing function
903   // bodies... this just adds external function prototypes to the Dest
904   // function...  We do this so that when we begin processing function bodies,
905   // all of the global values that may be referenced are available in our
906   // ValueMap.
907   //
908   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
909
910   // Update the initializers in the Dest module now that all globals that may
911   // be referenced are in Dest.
912   //
913   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
914
915   // Link in the function bodies that are defined in the source module into the
916   // DestModule.  This consists basically of copying the function over and
917   // fixing up references to values.
918   //
919   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
920
921   // If there were any appending global variables, link them together now.
922   //
923   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
924
925   return false;
926 }
927