3b1fcebffcf7cb5f221491e1f13fb5cfda984f7b
[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 is distributed under the University of Illinois Open Source
6 // 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/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/Support/Streams.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include <sstream>
33 using namespace llvm;
34
35 // Error - Simple wrapper function to conditionally assign to E and return true.
36 // This just makes error return conditions a little bit simpler...
37 static inline bool Error(std::string *E, const std::string &Message) {
38   if (E) *E = Message;
39   return true;
40 }
41
42 // Function: ResolveTypes()
43 //
44 // Description:
45 //  Attempt to link the two specified types together.
46 //
47 // Inputs:
48 //  DestTy - The type to which we wish to resolve.
49 //  SrcTy  - The original type which we want to resolve.
50 //
51 // Outputs:
52 //  DestST - The symbol table in which the new type should be placed.
53 //
54 // Return value:
55 //  true  - There is an error and the types cannot yet be linked.
56 //  false - No errors.
57 //
58 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
59   if (DestTy == SrcTy) return false;       // If already equal, noop
60   assert(DestTy && SrcTy && "Can't handle null types");
61
62   if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
63     // Type _is_ in module, just opaque...
64     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
65   } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
66     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
67   } else {
68     return true;  // Cannot link types... not-equal and neither is opaque.
69   }
70   return false;
71 }
72
73 /// LinkerTypeMap - This implements a map of types that is stable
74 /// even if types are resolved/refined to other types.  This is not a general
75 /// purpose map, it is specific to the linker's use.
76 namespace {
77 class LinkerTypeMap : public AbstractTypeUser {
78   typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
79   TheMapTy TheMap;
80
81   LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
82   void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
83 public:
84   LinkerTypeMap() {}
85   ~LinkerTypeMap() {
86     for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
87          E = TheMap.end(); I != E; ++I)
88       I->first->removeAbstractTypeUser(this);
89   }
90
91   /// lookup - Return the value for the specified type or null if it doesn't
92   /// exist.
93   const Type *lookup(const Type *Ty) const {
94     TheMapTy::const_iterator I = TheMap.find(Ty);
95     if (I != TheMap.end()) return I->second;
96     return 0;
97   }
98
99   /// erase - Remove the specified type, returning true if it was in the set.
100   bool erase(const Type *Ty) {
101     if (!TheMap.erase(Ty))
102       return false;
103     if (Ty->isAbstract())
104       Ty->removeAbstractTypeUser(this);
105     return true;
106   }
107
108   /// insert - This returns true if the pointer was new to the set, false if it
109   /// was already in the set.
110   bool insert(const Type *Src, const Type *Dst) {
111     if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
112       return false;  // Already in map.
113     if (Src->isAbstract())
114       Src->addAbstractTypeUser(this);
115     return true;
116   }
117
118 protected:
119   /// refineAbstractType - The callback method invoked when an abstract type is
120   /// resolved to another type.  An object must override this method to update
121   /// its internal state to reference NewType instead of OldType.
122   ///
123   virtual void refineAbstractType(const DerivedType *OldTy,
124                                   const Type *NewTy) {
125     TheMapTy::iterator I = TheMap.find(OldTy);
126     const Type *DstTy = I->second;
127
128     TheMap.erase(I);
129     if (OldTy->isAbstract())
130       OldTy->removeAbstractTypeUser(this);
131
132     // Don't reinsert into the map if the key is concrete now.
133     if (NewTy->isAbstract())
134       insert(NewTy, DstTy);
135   }
136
137   /// The other case which AbstractTypeUsers must be aware of is when a type
138   /// makes the transition from being abstract (where it has clients on it's
139   /// AbstractTypeUsers list) to concrete (where it does not).  This method
140   /// notifies ATU's when this occurs for a type.
141   virtual void typeBecameConcrete(const DerivedType *AbsTy) {
142     TheMap.erase(AbsTy);
143     AbsTy->removeAbstractTypeUser(this);
144   }
145
146   // for debugging...
147   virtual void dump() const {
148     cerr << "AbstractTypeSet!\n";
149   }
150 };
151 }
152
153
154 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
155 // recurses down into derived types, merging the used types if the parent types
156 // are compatible.
157 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
158                                    LinkerTypeMap &Pointers) {
159   if (DstTy == SrcTy) return false;       // If already equal, noop
160
161   // If we found our opaque type, resolve it now!
162   if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
163     return ResolveTypes(DstTy, SrcTy);
164
165   // Two types cannot be resolved together if they are of different primitive
166   // type.  For example, we cannot resolve an int to a float.
167   if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
168
169   // If neither type is abstract, then they really are just different types.
170   if (!DstTy->isAbstract() && !SrcTy->isAbstract())
171     return true;
172
173   // Otherwise, resolve the used type used by this derived type...
174   switch (DstTy->getTypeID()) {
175   default:
176     return true;
177   case Type::FunctionTyID: {
178     const FunctionType *DstFT = cast<FunctionType>(DstTy);
179     const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
180     if (DstFT->isVarArg() != SrcFT->isVarArg() ||
181         DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
182       return true;
183
184     // Use TypeHolder's so recursive resolution won't break us.
185     PATypeHolder ST(SrcFT), DT(DstFT);
186     for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
187       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
188       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
189         return true;
190     }
191     return false;
192   }
193   case Type::StructTyID: {
194     const StructType *DstST = cast<StructType>(DstTy);
195     const StructType *SrcST = cast<StructType>(SrcTy);
196     if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
197       return true;
198
199     PATypeHolder ST(SrcST), DT(DstST);
200     for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
201       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
202       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
203         return true;
204     }
205     return false;
206   }
207   case Type::ArrayTyID: {
208     const ArrayType *DAT = cast<ArrayType>(DstTy);
209     const ArrayType *SAT = cast<ArrayType>(SrcTy);
210     if (DAT->getNumElements() != SAT->getNumElements()) return true;
211     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
212                                   Pointers);
213   }
214   case Type::VectorTyID: {
215     const VectorType *DVT = cast<VectorType>(DstTy);
216     const VectorType *SVT = cast<VectorType>(SrcTy);
217     if (DVT->getNumElements() != SVT->getNumElements()) return true;
218     return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
219                                   Pointers);
220   }
221   case Type::PointerTyID: {
222     const PointerType *DstPT = cast<PointerType>(DstTy);
223     const PointerType *SrcPT = cast<PointerType>(SrcTy);
224
225     if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
226       return true;
227
228     // If this is a pointer type, check to see if we have already seen it.  If
229     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
230     // an associative container for this search, because the type pointers (keys
231     // in the container) change whenever types get resolved.
232     if (SrcPT->isAbstract())
233       if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
234         return ExistingDestTy != DstPT;
235
236     if (DstPT->isAbstract())
237       if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
238         return ExistingSrcTy != SrcPT;
239     // Otherwise, add the current pointers to the vector to stop recursion on
240     // this pair.
241     if (DstPT->isAbstract())
242       Pointers.insert(DstPT, SrcPT);
243     if (SrcPT->isAbstract())
244       Pointers.insert(SrcPT, DstPT);
245
246     return RecursiveResolveTypesI(DstPT->getElementType(),
247                                   SrcPT->getElementType(), Pointers);
248   }
249   }
250 }
251
252 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
253   LinkerTypeMap PointerTypes;
254   return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
255 }
256
257
258 // LinkTypes - Go through the symbol table of the Src module and see if any
259 // types are named in the src module that are not named in the Dst module.
260 // Make sure there are no type name conflicts.
261 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
262         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
263   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
264
265   // Look for a type plane for Type's...
266   TypeSymbolTable::const_iterator TI = SrcST->begin();
267   TypeSymbolTable::const_iterator TE = SrcST->end();
268   if (TI == TE) return false;  // No named types, do nothing.
269
270   // Some types cannot be resolved immediately because they depend on other
271   // types being resolved to each other first.  This contains a list of types we
272   // are waiting to recheck.
273   std::vector<std::string> DelayedTypesToResolve;
274
275   for ( ; TI != TE; ++TI ) {
276     const std::string &Name = TI->first;
277     const Type *RHS = TI->second;
278
279     // Check to see if this type name is already in the dest module.
280     Type *Entry = DestST->lookup(Name);
281
282     // If the name is just in the source module, bring it over to the dest.
283     if (Entry == 0) {
284       if (!Name.empty())
285         DestST->insert(Name, const_cast<Type*>(RHS));
286     } else if (ResolveTypes(Entry, RHS)) {
287       // They look different, save the types 'till later to resolve.
288       DelayedTypesToResolve.push_back(Name);
289     }
290   }
291
292   // Iteratively resolve types while we can...
293   while (!DelayedTypesToResolve.empty()) {
294     // Loop over all of the types, attempting to resolve them if possible...
295     unsigned OldSize = DelayedTypesToResolve.size();
296
297     // Try direct resolution by name...
298     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
299       const std::string &Name = DelayedTypesToResolve[i];
300       Type *T1 = SrcST->lookup(Name);
301       Type *T2 = DestST->lookup(Name);
302       if (!ResolveTypes(T2, T1)) {
303         // We are making progress!
304         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
305         --i;
306       }
307     }
308
309     // Did we not eliminate any types?
310     if (DelayedTypesToResolve.size() == OldSize) {
311       // Attempt to resolve subelements of types.  This allows us to merge these
312       // two types: { int* } and { opaque* }
313       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
314         const std::string &Name = DelayedTypesToResolve[i];
315         if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
316           // We are making progress!
317           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
318
319           // Go back to the main loop, perhaps we can resolve directly by name
320           // now...
321           break;
322         }
323       }
324
325       // If we STILL cannot resolve the types, then there is something wrong.
326       if (DelayedTypesToResolve.size() == OldSize) {
327         // Remove the symbol name from the destination.
328         DelayedTypesToResolve.pop_back();
329       }
330     }
331   }
332
333
334   return false;
335 }
336
337 #ifndef NDEBUG
338 static void PrintMap(const std::map<const Value*, Value*> &M) {
339   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
340        I != E; ++I) {
341     cerr << " Fr: " << (void*)I->first << " ";
342     I->first->dump();
343     cerr << " To: " << (void*)I->second << " ";
344     I->second->dump();
345     cerr << "\n";
346   }
347 }
348 #endif
349
350
351 // RemapOperand - Use ValueMap to convert constants from one module to another.
352 static Value *RemapOperand(const Value *In,
353                            std::map<const Value*, Value*> &ValueMap,
354                            LLVMContext &Context) {
355   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
356   if (I != ValueMap.end())
357     return I->second;
358
359   // Check to see if it's a constant that we are interested in transforming.
360   Value *Result = 0;
361   if (const Constant *CPV = dyn_cast<Constant>(In)) {
362     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
363         isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
364       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
365
366     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
367       std::vector<Constant*> Operands(CPA->getNumOperands());
368       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
369         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap, 
370                                                  Context));
371       Result =
372           Context.getConstantArray(cast<ArrayType>(CPA->getType()), Operands);
373     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
374       std::vector<Constant*> Operands(CPS->getNumOperands());
375       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
376         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap,
377                                                  Context));
378       Result =
379          Context.getConstantStruct(cast<StructType>(CPS->getType()), Operands);
380     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
381       Result = const_cast<Constant*>(CPV);
382     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
383       std::vector<Constant*> Operands(CP->getNumOperands());
384       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
385         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap,
386                                      Context));
387       Result = Context.getConstantVector(Operands);
388     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
389       std::vector<Constant*> Ops;
390       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
391         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap,
392                                      Context)));
393       Result = CE->getWithOperands(Ops);
394     } else {
395       assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
396       LLVM_UNREACHABLE("Unknown type of derived type constant value!");
397     }
398   } else if (isa<InlineAsm>(In)) {
399     Result = const_cast<Value*>(In);
400   }
401
402   // Cache the mapping in our local map structure
403   if (Result) {
404     ValueMap[In] = Result;
405     return Result;
406   }
407
408 #ifndef NDEBUG
409   cerr << "LinkModules ValueMap: \n";
410   PrintMap(ValueMap);
411
412   cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
413   LLVM_UNREACHABLE("Couldn't remap value!");
414 #endif
415   return 0;
416 }
417
418 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
419 /// in the symbol table.  This is good for all clients except for us.  Go
420 /// through the trouble to force this back.
421 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
422   assert(GV->getName() != Name && "Can't force rename to self");
423   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
424
425   // If there is a conflict, rename the conflict.
426   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
427     assert(ConflictGV->hasLocalLinkage() &&
428            "Not conflicting with a static global, should link instead!");
429     GV->takeName(ConflictGV);
430     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
431     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
432   } else {
433     GV->setName(Name);              // Force the name back
434   }
435 }
436
437 /// CopyGVAttributes - copy additional attributes (those not needed to construct
438 /// a GlobalValue) from the SrcGV to the DestGV.
439 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
440   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
441   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
442   DestGV->copyAttributesFrom(SrcGV);
443   DestGV->setAlignment(Alignment);
444 }
445
446 /// GetLinkageResult - This analyzes the two global values and determines what
447 /// the result will look like in the destination module.  In particular, it
448 /// computes the resultant linkage type, computes whether the global in the
449 /// source should be copied over to the destination (replacing the existing
450 /// one), and computes whether this linkage is an error or not. It also performs
451 /// visibility checks: we cannot link together two symbols with different
452 /// visibilities.
453 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
454                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
455                              std::string *Err) {
456   assert((!Dest || !Src->hasLocalLinkage()) &&
457          "If Src has internal linkage, Dest shouldn't be set!");
458   if (!Dest) {
459     // Linking something to nothing.
460     LinkFromSrc = true;
461     LT = Src->getLinkage();
462   } else if (Src->isDeclaration()) {
463     // If Src is external or if both Src & Dest are external..  Just link the
464     // external globals, we aren't adding anything.
465     if (Src->hasDLLImportLinkage()) {
466       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
467       if (Dest->isDeclaration()) {
468         LinkFromSrc = true;
469         LT = Src->getLinkage();
470       }
471     } else if (Dest->hasExternalWeakLinkage()) {
472       // If the Dest is weak, use the source linkage.
473       LinkFromSrc = true;
474       LT = Src->getLinkage();
475     } else {
476       LinkFromSrc = false;
477       LT = Dest->getLinkage();
478     }
479   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
480     // If Dest is external but Src is not:
481     LinkFromSrc = true;
482     LT = Src->getLinkage();
483   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
484     if (Src->getLinkage() != Dest->getLinkage())
485       return Error(Err, "Linking globals named '" + Src->getName() +
486             "': can only link appending global with another appending global!");
487     LinkFromSrc = true; // Special cased.
488     LT = Src->getLinkage();
489   } else if (Src->isWeakForLinker()) {
490     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
491     // or DLL* linkage.
492     if (Dest->hasExternalWeakLinkage() ||
493         Dest->hasAvailableExternallyLinkage() ||
494         (Dest->hasLinkOnceLinkage() &&
495          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
496       LinkFromSrc = true;
497       LT = Src->getLinkage();
498     } else {
499       LinkFromSrc = false;
500       LT = Dest->getLinkage();
501     }
502   } else if (Dest->isWeakForLinker()) {
503     // At this point we know that Src has External* or DLL* linkage.
504     if (Src->hasExternalWeakLinkage()) {
505       LinkFromSrc = false;
506       LT = Dest->getLinkage();
507     } else {
508       LinkFromSrc = true;
509       LT = GlobalValue::ExternalLinkage;
510     }
511   } else {
512     assert((Dest->hasExternalLinkage() ||
513             Dest->hasDLLImportLinkage() ||
514             Dest->hasDLLExportLinkage() ||
515             Dest->hasExternalWeakLinkage()) &&
516            (Src->hasExternalLinkage() ||
517             Src->hasDLLImportLinkage() ||
518             Src->hasDLLExportLinkage() ||
519             Src->hasExternalWeakLinkage()) &&
520            "Unexpected linkage type!");
521     return Error(Err, "Linking globals named '" + Src->getName() +
522                  "': symbol multiply defined!");
523   }
524
525   // Check visibility
526   if (Dest && Src->getVisibility() != Dest->getVisibility())
527     if (!Src->isDeclaration() && !Dest->isDeclaration())
528       return Error(Err, "Linking globals named '" + Src->getName() +
529                    "': symbols have different visibilities!");
530   return false;
531 }
532
533 // LinkGlobals - Loop through the global variables in the src module and merge
534 // them into the dest module.
535 static bool LinkGlobals(Module *Dest, const Module *Src,
536                         std::map<const Value*, Value*> &ValueMap,
537                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
538                         std::string *Err) {
539   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
540   LLVMContext &Context = Dest->getContext();
541
542   // Loop over all of the globals in the src module, mapping them over as we go
543   for (Module::const_global_iterator I = Src->global_begin(),
544        E = Src->global_end(); I != E; ++I) {
545     const GlobalVariable *SGV = I;
546     GlobalValue *DGV = 0;
547
548     // Check to see if may have to link the global with the global, alias or
549     // function.
550     if (SGV->hasName() && !SGV->hasLocalLinkage())
551       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getNameStart(),
552                                                         SGV->getNameEnd()));
553
554     // If we found a global with the same name in the dest module, but it has
555     // internal linkage, we are really not doing any linkage here.
556     if (DGV && DGV->hasLocalLinkage())
557       DGV = 0;
558
559     // If types don't agree due to opaque types, try to resolve them.
560     if (DGV && DGV->getType() != SGV->getType())
561       RecursiveResolveTypes(SGV->getType(), DGV->getType());
562
563     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
564             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
565            "Global must either be external or have an initializer!");
566
567     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
568     bool LinkFromSrc = false;
569     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
570       return true;
571
572     if (DGV == 0) {
573       // No linking to be performed, simply create an identical version of the
574       // symbol over in the dest module... the initializer will be filled in
575       // later by LinkGlobalInits.
576       GlobalVariable *NewDGV =
577         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
578                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
579                            SGV->getName(), 0, false,
580                            SGV->getType()->getAddressSpace());
581       // Propagate alignment, visibility and section info.
582       CopyGVAttributes(NewDGV, SGV);
583
584       // If the LLVM runtime renamed the global, but it is an externally visible
585       // symbol, DGV must be an existing global with internal linkage.  Rename
586       // it.
587       if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
588         ForceRenaming(NewDGV, SGV->getName());
589
590       // Make sure to remember this mapping.
591       ValueMap[SGV] = NewDGV;
592
593       // Keep track that this is an appending variable.
594       if (SGV->hasAppendingLinkage())
595         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
596       continue;
597     }
598
599     // If the visibilities of the symbols disagree and the destination is a
600     // prototype, take the visibility of its input.
601     if (DGV->isDeclaration())
602       DGV->setVisibility(SGV->getVisibility());
603
604     if (DGV->hasAppendingLinkage()) {
605       // No linking is performed yet.  Just insert a new copy of the global, and
606       // keep track of the fact that it is an appending variable in the
607       // AppendingVars map.  The name is cleared out so that no linkage is
608       // performed.
609       GlobalVariable *NewDGV =
610         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
611                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
612                            "", 0, false,
613                            SGV->getType()->getAddressSpace());
614
615       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
616       NewDGV->setAlignment(DGV->getAlignment());
617       // Propagate alignment, section and visibility info.
618       CopyGVAttributes(NewDGV, SGV);
619
620       // Make sure to remember this mapping...
621       ValueMap[SGV] = NewDGV;
622
623       // Keep track that this is an appending variable...
624       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
625       continue;
626     }
627
628     if (LinkFromSrc) {
629       if (isa<GlobalAlias>(DGV))
630         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
631                      "': symbol multiple defined");
632
633       // If the types don't match, and if we are to link from the source, nuke
634       // DGV and create a new one of the appropriate type.  Note that the thing
635       // we are replacing may be a function (if a prototype, weak, etc) or a
636       // global variable.
637       GlobalVariable *NewDGV =
638         new GlobalVariable(*Dest, SGV->getType()->getElementType(), 
639                            SGV->isConstant(), NewLinkage, /*init*/0, 
640                            DGV->getName(), 0, false,
641                            SGV->getType()->getAddressSpace());
642
643       // Propagate alignment, section, and visibility info.
644       CopyGVAttributes(NewDGV, SGV);
645       DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDGV, 
646                                                               DGV->getType()));
647
648       // DGV will conflict with NewDGV because they both had the same
649       // name. We must erase this now so ForceRenaming doesn't assert
650       // because DGV might not have internal linkage.
651       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
652         Var->eraseFromParent();
653       else
654         cast<Function>(DGV)->eraseFromParent();
655       DGV = NewDGV;
656
657       // If the symbol table renamed the global, but it is an externally visible
658       // symbol, DGV must be an existing global with internal linkage.  Rename.
659       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
660         ForceRenaming(NewDGV, SGV->getName());
661
662       // Inherit const as appropriate.
663       NewDGV->setConstant(SGV->isConstant());
664
665       // Make sure to remember this mapping.
666       ValueMap[SGV] = NewDGV;
667       continue;
668     }
669
670     // Not "link from source", keep the one in the DestModule and remap the
671     // input onto it.
672
673     // Special case for const propagation.
674     if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
675       if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
676         DGVar->setConstant(true);
677
678     // SGV is global, but DGV is alias.
679     if (isa<GlobalAlias>(DGV)) {
680       // The only valid mappings are:
681       // - SGV is external declaration, which is effectively a no-op.
682       // - SGV is weak, when we just need to throw SGV out.
683       if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
684         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
685                      "': symbol multiple defined");
686     }
687
688     // Set calculated linkage
689     DGV->setLinkage(NewLinkage);
690
691     // Make sure to remember this mapping...
692     ValueMap[SGV] = Context.getConstantExprBitCast(DGV, SGV->getType());
693   }
694   return false;
695 }
696
697 static GlobalValue::LinkageTypes
698 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
699   GlobalValue::LinkageTypes SL = SGV->getLinkage();
700   GlobalValue::LinkageTypes DL = DGV->getLinkage();
701   if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
702     return GlobalValue::ExternalLinkage;
703   else if (SL == GlobalValue::WeakAnyLinkage ||
704            DL == GlobalValue::WeakAnyLinkage)
705     return GlobalValue::WeakAnyLinkage;
706   else if (SL == GlobalValue::WeakODRLinkage ||
707            DL == GlobalValue::WeakODRLinkage)
708     return GlobalValue::WeakODRLinkage;
709   else if (SL == GlobalValue::InternalLinkage &&
710            DL == GlobalValue::InternalLinkage)
711     return GlobalValue::InternalLinkage;
712   else {
713     assert (SL == GlobalValue::PrivateLinkage &&
714             DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
715     return GlobalValue::PrivateLinkage;
716   }
717 }
718
719 // LinkAlias - Loop through the alias in the src module and link them into the
720 // dest module. We're assuming, that all functions/global variables were already
721 // linked in.
722 static bool LinkAlias(Module *Dest, const Module *Src,
723                       std::map<const Value*, Value*> &ValueMap,
724                       std::string *Err) {
725   LLVMContext &Context = Dest->getContext();
726
727   // Loop over all alias in the src module
728   for (Module::const_alias_iterator I = Src->alias_begin(),
729          E = Src->alias_end(); I != E; ++I) {
730     const GlobalAlias *SGA = I;
731     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
732     GlobalAlias *NewGA = NULL;
733
734     // Globals were already linked, thus we can just query ValueMap for variant
735     // of SAliasee in Dest.
736     std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
737     assert(VMI != ValueMap.end() && "Aliasee not linked");
738     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
739     GlobalValue* DGV = NULL;
740
741     // Try to find something 'similar' to SGA in destination module.
742     if (!DGV && !SGA->hasLocalLinkage()) {
743       DGV = Dest->getNamedAlias(SGA->getName());
744
745       // If types don't agree due to opaque types, try to resolve them.
746       if (DGV && DGV->getType() != SGA->getType())
747         RecursiveResolveTypes(SGA->getType(), DGV->getType());
748     }
749
750     if (!DGV && !SGA->hasLocalLinkage()) {
751       DGV = Dest->getGlobalVariable(SGA->getName());
752
753       // If types don't agree due to opaque types, try to resolve them.
754       if (DGV && DGV->getType() != SGA->getType())
755         RecursiveResolveTypes(SGA->getType(), DGV->getType());
756     }
757
758     if (!DGV && !SGA->hasLocalLinkage()) {
759       DGV = Dest->getFunction(SGA->getName());
760
761       // If types don't agree due to opaque types, try to resolve them.
762       if (DGV && DGV->getType() != SGA->getType())
763         RecursiveResolveTypes(SGA->getType(), DGV->getType());
764     }
765
766     // No linking to be performed on internal stuff.
767     if (DGV && DGV->hasLocalLinkage())
768       DGV = NULL;
769
770     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
771       // Types are known to be the same, check whether aliasees equal. As
772       // globals are already linked we just need query ValueMap to find the
773       // mapping.
774       if (DAliasee == DGA->getAliasedGlobal()) {
775         // This is just two copies of the same alias. Propagate linkage, if
776         // necessary.
777         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
778
779         NewGA = DGA;
780         // Proceed to 'common' steps
781       } else
782         return Error(Err, "Alias Collision on '"  + SGA->getName()+
783                      "': aliases have different aliasees");
784     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
785       // The only allowed way is to link alias with external declaration or weak
786       // symbol..
787       if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
788         // But only if aliasee is global too...
789         if (!isa<GlobalVariable>(DAliasee))
790           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
791                        "': aliasee is not global variable");
792
793         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
794                                 SGA->getName(), DAliasee, Dest);
795         CopyGVAttributes(NewGA, SGA);
796
797         // Any uses of DGV need to change to NewGA, with cast, if needed.
798         if (SGA->getType() != DGVar->getType())
799           DGVar->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
800                                                              DGVar->getType()));
801         else
802           DGVar->replaceAllUsesWith(NewGA);
803
804         // DGVar will conflict with NewGA because they both had the same
805         // name. We must erase this now so ForceRenaming doesn't assert
806         // because DGV might not have internal linkage.
807         DGVar->eraseFromParent();
808
809         // Proceed to 'common' steps
810       } else
811         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
812                      "': symbol multiple defined");
813     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
814       // The only allowed way is to link alias with external declaration or weak
815       // symbol...
816       if (DF->isDeclaration() || DF->isWeakForLinker()) {
817         // But only if aliasee is function too...
818         if (!isa<Function>(DAliasee))
819           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
820                        "': aliasee is not function");
821
822         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
823                                 SGA->getName(), DAliasee, Dest);
824         CopyGVAttributes(NewGA, SGA);
825
826         // Any uses of DF need to change to NewGA, with cast, if needed.
827         if (SGA->getType() != DF->getType())
828           DF->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
829                                                           DF->getType()));
830         else
831           DF->replaceAllUsesWith(NewGA);
832
833         // DF will conflict with NewGA because they both had the same
834         // name. We must erase this now so ForceRenaming doesn't assert
835         // because DF might not have internal linkage.
836         DF->eraseFromParent();
837
838         // Proceed to 'common' steps
839       } else
840         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
841                      "': symbol multiple defined");
842     } else {
843       // No linking to be performed, simply create an identical version of the
844       // alias over in the dest module...
845
846       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
847                               SGA->getName(), DAliasee, Dest);
848       CopyGVAttributes(NewGA, SGA);
849
850       // Proceed to 'common' steps
851     }
852
853     assert(NewGA && "No alias was created in destination module!");
854
855     // If the symbol table renamed the alias, but it is an externally visible
856     // symbol, DGA must be an global value with internal linkage. Rename it.
857     if (NewGA->getName() != SGA->getName() &&
858         !NewGA->hasLocalLinkage())
859       ForceRenaming(NewGA, SGA->getName());
860
861     // Remember this mapping so uses in the source module get remapped
862     // later by RemapOperand.
863     ValueMap[SGA] = NewGA;
864   }
865
866   return false;
867 }
868
869
870 // LinkGlobalInits - Update the initializers in the Dest module now that all
871 // globals that may be referenced are in Dest.
872 static bool LinkGlobalInits(Module *Dest, const Module *Src,
873                             std::map<const Value*, Value*> &ValueMap,
874                             std::string *Err) {
875   // Loop over all of the globals in the src module, mapping them over as we go
876   for (Module::const_global_iterator I = Src->global_begin(),
877        E = Src->global_end(); I != E; ++I) {
878     const GlobalVariable *SGV = I;
879
880     if (SGV->hasInitializer()) {      // Only process initialized GV's
881       // Figure out what the initializer looks like in the dest module...
882       Constant *SInit =
883         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap,
884                        Dest->getContext()));
885       // Grab destination global variable or alias.
886       GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
887
888       // If dest if global variable, check that initializers match.
889       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
890         if (DGVar->hasInitializer()) {
891           if (SGV->hasExternalLinkage()) {
892             if (DGVar->getInitializer() != SInit)
893               return Error(Err, "Global Variable Collision on '" +
894                            SGV->getName() +
895                            "': global variables have different initializers");
896           } else if (DGVar->isWeakForLinker()) {
897             // Nothing is required, mapped values will take the new global
898             // automatically.
899           } else if (SGV->isWeakForLinker()) {
900             // Nothing is required, mapped values will take the new global
901             // automatically.
902           } else if (DGVar->hasAppendingLinkage()) {
903             LLVM_UNREACHABLE("Appending linkage unimplemented!");
904           } else {
905             LLVM_UNREACHABLE("Unknown linkage!");
906           }
907         } else {
908           // Copy the initializer over now...
909           DGVar->setInitializer(SInit);
910         }
911       } else {
912         // Destination is alias, the only valid situation is when source is
913         // weak. Also, note, that we already checked linkage in LinkGlobals(),
914         // thus we assert here.
915         // FIXME: Should we weaken this assumption, 'dereference' alias and
916         // check for initializer of aliasee?
917         assert(SGV->isWeakForLinker());
918       }
919     }
920   }
921   return false;
922 }
923
924 // LinkFunctionProtos - Link the functions together between the two modules,
925 // without doing function bodies... this just adds external function prototypes
926 // to the Dest function...
927 //
928 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
929                                std::map<const Value*, Value*> &ValueMap,
930                                std::string *Err) {
931   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
932   LLVMContext &Context = Dest->getContext();
933
934   // Loop over all of the functions in the src module, mapping them over
935   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
936     const Function *SF = I;   // SrcFunction
937     GlobalValue *DGV = 0;
938
939     // Check to see if may have to link the function with the global, alias or
940     // function.
941     if (SF->hasName() && !SF->hasLocalLinkage())
942       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getNameStart(),
943                                                         SF->getNameEnd()));
944
945     // If we found a global with the same name in the dest module, but it has
946     // internal linkage, we are really not doing any linkage here.
947     if (DGV && DGV->hasLocalLinkage())
948       DGV = 0;
949
950     // If types don't agree due to opaque types, try to resolve them.
951     if (DGV && DGV->getType() != SF->getType())
952       RecursiveResolveTypes(SF->getType(), DGV->getType());
953
954     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
955     bool LinkFromSrc = false;
956     if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
957       return true;
958
959     // If there is no linkage to be performed, just bring over SF without
960     // modifying it.
961     if (DGV == 0) {
962       // Function does not already exist, simply insert an function signature
963       // identical to SF into the dest module.
964       Function *NewDF = Function::Create(SF->getFunctionType(),
965                                          SF->getLinkage(),
966                                          SF->getName(), Dest);
967       CopyGVAttributes(NewDF, SF);
968
969       // If the LLVM runtime renamed the function, but it is an externally
970       // visible symbol, DF must be an existing function with internal linkage.
971       // Rename it.
972       if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
973         ForceRenaming(NewDF, SF->getName());
974
975       // ... and remember this mapping...
976       ValueMap[SF] = NewDF;
977       continue;
978     }
979
980     // If the visibilities of the symbols disagree and the destination is a
981     // prototype, take the visibility of its input.
982     if (DGV->isDeclaration())
983       DGV->setVisibility(SF->getVisibility());
984
985     if (LinkFromSrc) {
986       if (isa<GlobalAlias>(DGV))
987         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
988                      "': symbol multiple defined");
989
990       // We have a definition of the same name but different type in the
991       // source module. Copy the prototype to the destination and replace
992       // uses of the destination's prototype with the new prototype.
993       Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
994                                          SF->getName(), Dest);
995       CopyGVAttributes(NewDF, SF);
996
997       // Any uses of DF need to change to NewDF, with cast
998       DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDF, 
999                                                               DGV->getType()));
1000
1001       // DF will conflict with NewDF because they both had the same. We must
1002       // erase this now so ForceRenaming doesn't assert because DF might
1003       // not have internal linkage.
1004       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1005         Var->eraseFromParent();
1006       else
1007         cast<Function>(DGV)->eraseFromParent();
1008
1009       // If the symbol table renamed the function, but it is an externally
1010       // visible symbol, DF must be an existing function with internal
1011       // linkage.  Rename it.
1012       if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
1013         ForceRenaming(NewDF, SF->getName());
1014
1015       // Remember this mapping so uses in the source module get remapped
1016       // later by RemapOperand.
1017       ValueMap[SF] = NewDF;
1018       continue;
1019     }
1020
1021     // Not "link from source", keep the one in the DestModule and remap the
1022     // input onto it.
1023
1024     if (isa<GlobalAlias>(DGV)) {
1025       // The only valid mappings are:
1026       // - SF is external declaration, which is effectively a no-op.
1027       // - SF is weak, when we just need to throw SF out.
1028       if (!SF->isDeclaration() && !SF->isWeakForLinker())
1029         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1030                      "': symbol multiple defined");
1031     }
1032
1033     // Set calculated linkage
1034     DGV->setLinkage(NewLinkage);
1035
1036     // Make sure to remember this mapping.
1037     ValueMap[SF] = Context.getConstantExprBitCast(DGV, SF->getType());
1038   }
1039   return false;
1040 }
1041
1042 // LinkFunctionBody - Copy the source function over into the dest function and
1043 // fix up references to values.  At this point we know that Dest is an external
1044 // function, and that Src is not.
1045 static bool LinkFunctionBody(Function *Dest, Function *Src,
1046                              std::map<const Value*, Value*> &ValueMap,
1047                              std::string *Err) {
1048   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1049
1050   // Go through and convert function arguments over, remembering the mapping.
1051   Function::arg_iterator DI = Dest->arg_begin();
1052   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1053        I != E; ++I, ++DI) {
1054     DI->setName(I->getName());  // Copy the name information over...
1055
1056     // Add a mapping to our local map
1057     ValueMap[I] = DI;
1058   }
1059
1060   // Splice the body of the source function into the dest function.
1061   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1062
1063   // At this point, all of the instructions and values of the function are now
1064   // copied over.  The only problem is that they are still referencing values in
1065   // the Source function as operands.  Loop through all of the operands of the
1066   // functions and patch them up to point to the local versions...
1067   //
1068   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1069     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1070       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1071            OI != OE; ++OI)
1072         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1073           *OI = RemapOperand(*OI, ValueMap, *Dest->getContext());
1074
1075   // There is no need to map the arguments anymore.
1076   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1077        I != E; ++I)
1078     ValueMap.erase(I);
1079
1080   return false;
1081 }
1082
1083
1084 // LinkFunctionBodies - Link in the function bodies that are defined in the
1085 // source module into the DestModule.  This consists basically of copying the
1086 // function over and fixing up references to values.
1087 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1088                                std::map<const Value*, Value*> &ValueMap,
1089                                std::string *Err) {
1090
1091   // Loop over all of the functions in the src module, mapping them over as we
1092   // go
1093   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1094     if (!SF->isDeclaration()) {               // No body if function is external
1095       Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1096
1097       // DF not external SF external?
1098       if (DF && DF->isDeclaration())
1099         // Only provide the function body if there isn't one already.
1100         if (LinkFunctionBody(DF, SF, ValueMap, Err))
1101           return true;
1102     }
1103   }
1104   return false;
1105 }
1106
1107 // LinkAppendingVars - If there were any appending global variables, link them
1108 // together now.  Return true on error.
1109 static bool LinkAppendingVars(Module *M,
1110                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
1111                               std::string *ErrorMsg) {
1112   if (AppendingVars.empty()) return false; // Nothing to do.
1113
1114   LLVMContext &Context = M->getContext();
1115
1116   // Loop over the multimap of appending vars, processing any variables with the
1117   // same name, forming a new appending global variable with both of the
1118   // initializers merged together, then rewrite references to the old variables
1119   // and delete them.
1120   std::vector<Constant*> Inits;
1121   while (AppendingVars.size() > 1) {
1122     // Get the first two elements in the map...
1123     std::multimap<std::string,
1124       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1125
1126     // If the first two elements are for different names, there is no pair...
1127     // Otherwise there is a pair, so link them together...
1128     if (First->first == Second->first) {
1129       GlobalVariable *G1 = First->second, *G2 = Second->second;
1130       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1131       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1132
1133       // Check to see that they two arrays agree on type...
1134       if (T1->getElementType() != T2->getElementType())
1135         return Error(ErrorMsg,
1136          "Appending variables with different element types need to be linked!");
1137       if (G1->isConstant() != G2->isConstant())
1138         return Error(ErrorMsg,
1139                      "Appending variables linked with different const'ness!");
1140
1141       if (G1->getAlignment() != G2->getAlignment())
1142         return Error(ErrorMsg,
1143          "Appending variables with different alignment need to be linked!");
1144
1145       if (G1->getVisibility() != G2->getVisibility())
1146         return Error(ErrorMsg,
1147          "Appending variables with different visibility need to be linked!");
1148
1149       if (G1->getSection() != G2->getSection())
1150         return Error(ErrorMsg,
1151          "Appending variables with different section name need to be linked!");
1152
1153       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1154       ArrayType *NewType = Context.getArrayType(T1->getElementType(), 
1155                                                          NewSize);
1156
1157       G1->setName("");   // Clear G1's name in case of a conflict!
1158
1159       // Create the new global variable...
1160       GlobalVariable *NG =
1161         new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1162                            /*init*/0, First->first, 0, G1->isThreadLocal(),
1163                            G1->getType()->getAddressSpace());
1164
1165       // Propagate alignment, visibility and section info.
1166       CopyGVAttributes(NG, G1);
1167
1168       // Merge the initializer...
1169       Inits.reserve(NewSize);
1170       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1171         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1172           Inits.push_back(I->getOperand(i));
1173       } else {
1174         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1175         Constant *CV = Context.getNullValue(T1->getElementType());
1176         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1177           Inits.push_back(CV);
1178       }
1179       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1180         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1181           Inits.push_back(I->getOperand(i));
1182       } else {
1183         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1184         Constant *CV = Context.getNullValue(T2->getElementType());
1185         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1186           Inits.push_back(CV);
1187       }
1188       NG->setInitializer(Context.getConstantArray(NewType, Inits));
1189       Inits.clear();
1190
1191       // Replace any uses of the two global variables with uses of the new
1192       // global...
1193
1194       // FIXME: This should rewrite simple/straight-forward uses such as
1195       // getelementptr instructions to not use the Cast!
1196       G1->replaceAllUsesWith(Context.getConstantExprBitCast(NG,
1197                              G1->getType()));
1198       G2->replaceAllUsesWith(Context.getConstantExprBitCast(NG, 
1199                              G2->getType()));
1200
1201       // Remove the two globals from the module now...
1202       M->getGlobalList().erase(G1);
1203       M->getGlobalList().erase(G2);
1204
1205       // Put the new global into the AppendingVars map so that we can handle
1206       // linking of more than two vars...
1207       Second->second = NG;
1208     }
1209     AppendingVars.erase(First);
1210   }
1211
1212   return false;
1213 }
1214
1215 static bool ResolveAliases(Module *Dest) {
1216   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1217        I != E; ++I)
1218     if (const GlobalValue *GV = I->resolveAliasedGlobal())
1219       if (GV != I && !GV->isDeclaration())
1220         I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
1221
1222   return false;
1223 }
1224
1225 // LinkModules - This function links two modules together, with the resulting
1226 // left module modified to be the composite of the two input modules.  If an
1227 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1228 // the problem.  Upon failure, the Dest module could be in a modified state, and
1229 // shouldn't be relied on to be consistent.
1230 bool
1231 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1232   assert(Dest != 0 && "Invalid Destination module");
1233   assert(Src  != 0 && "Invalid Source Module");
1234
1235   if (Dest->getDataLayout().empty()) {
1236     if (!Src->getDataLayout().empty()) {
1237       Dest->setDataLayout(Src->getDataLayout());
1238     } else {
1239       std::string DataLayout;
1240
1241       if (Dest->getEndianness() == Module::AnyEndianness) {
1242         if (Src->getEndianness() == Module::BigEndian)
1243           DataLayout.append("E");
1244         else if (Src->getEndianness() == Module::LittleEndian)
1245           DataLayout.append("e");
1246       }
1247
1248       if (Dest->getPointerSize() == Module::AnyPointerSize) {
1249         if (Src->getPointerSize() == Module::Pointer64)
1250           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1251         else if (Src->getPointerSize() == Module::Pointer32)
1252           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1253       }
1254       Dest->setDataLayout(DataLayout);
1255     }
1256   }
1257
1258   // Copy the target triple from the source to dest if the dest's is empty.
1259   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1260     Dest->setTargetTriple(Src->getTargetTriple());
1261
1262   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1263       Src->getDataLayout() != Dest->getDataLayout())
1264     cerr << "WARNING: Linking two modules of different data layouts!\n";
1265   if (!Src->getTargetTriple().empty() &&
1266       Dest->getTargetTriple() != Src->getTargetTriple())
1267     cerr << "WARNING: Linking two modules of different target triples!\n";
1268
1269   // Append the module inline asm string.
1270   if (!Src->getModuleInlineAsm().empty()) {
1271     if (Dest->getModuleInlineAsm().empty())
1272       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1273     else
1274       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1275                                Src->getModuleInlineAsm());
1276   }
1277
1278   // Update the destination module's dependent libraries list with the libraries
1279   // from the source module. There's no opportunity for duplicates here as the
1280   // Module ensures that duplicate insertions are discarded.
1281   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1282        SI != SE; ++SI)
1283     Dest->addLibrary(*SI);
1284
1285   // LinkTypes - Go through the symbol table of the Src module and see if any
1286   // types are named in the src module that are not named in the Dst module.
1287   // Make sure there are no type name conflicts.
1288   if (LinkTypes(Dest, Src, ErrorMsg))
1289     return true;
1290
1291   // ValueMap - Mapping of values from what they used to be in Src, to what they
1292   // are now in Dest.
1293   std::map<const Value*, Value*> ValueMap;
1294
1295   // AppendingVars - Keep track of global variables in the destination module
1296   // with appending linkage.  After the module is linked together, they are
1297   // appended and the module is rewritten.
1298   std::multimap<std::string, GlobalVariable *> AppendingVars;
1299   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1300        I != E; ++I) {
1301     // Add all of the appending globals already in the Dest module to
1302     // AppendingVars.
1303     if (I->hasAppendingLinkage())
1304       AppendingVars.insert(std::make_pair(I->getName(), I));
1305   }
1306
1307   // Insert all of the globals in src into the Dest module... without linking
1308   // initializers (which could refer to functions not yet mapped over).
1309   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1310     return true;
1311
1312   // Link the functions together between the two modules, without doing function
1313   // bodies... this just adds external function prototypes to the Dest
1314   // function...  We do this so that when we begin processing function bodies,
1315   // all of the global values that may be referenced are available in our
1316   // ValueMap.
1317   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1318     return true;
1319
1320   // If there were any alias, link them now. We really need to do this now,
1321   // because all of the aliases that may be referenced need to be available in
1322   // ValueMap
1323   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1324
1325   // Update the initializers in the Dest module now that all globals that may
1326   // be referenced are in Dest.
1327   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1328
1329   // Link in the function bodies that are defined in the source module into the
1330   // DestModule.  This consists basically of copying the function over and
1331   // fixing up references to values.
1332   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1333
1334   // If there were any appending global variables, link them together now.
1335   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1336
1337   // Resolve all uses of aliases with aliasees
1338   if (ResolveAliases(Dest)) return true;
1339
1340   // If the source library's module id is in the dependent library list of the
1341   // destination library, remove it since that module is now linked in.
1342   sys::Path modId;
1343   modId.set(Src->getModuleIdentifier());
1344   if (!modId.isEmpty())
1345     Dest->removeLibrary(modId.getBasename());
1346
1347   return false;
1348 }
1349
1350 // vim: sw=2