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