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