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