Change errs() to dbgs().
[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/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/System/Path.h"
32 #include "llvm/ADT/DenseMap.h"
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 Twine &Message) {
38   if (E) *E = Message.str();
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     dbgs() << "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     dbgs() << " Fr: " << (void*)I->first << " ";
342     I->first->dump();
343     dbgs() << " To: " << (void*)I->second << " ";
344     I->second->dump();
345     dbgs() << "\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   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
355   if (I != ValueMap.end())
356     return I->second;
357
358   // Check to see if it's a constant that we are interested in transforming.
359   Value *Result = 0;
360   if (const Constant *CPV = dyn_cast<Constant>(In)) {
361     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
362         isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
363       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
364
365     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
366       std::vector<Constant*> Operands(CPA->getNumOperands());
367       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
368         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
369       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
370     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
371       std::vector<Constant*> Operands(CPS->getNumOperands());
372       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
373         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
374       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
375     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
376       Result = const_cast<Constant*>(CPV);
377     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
378       std::vector<Constant*> Operands(CP->getNumOperands());
379       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
380         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
381       Result = ConstantVector::get(Operands);
382     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
383       std::vector<Constant*> Ops;
384       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
385         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
386       Result = CE->getWithOperands(Ops);
387     } else if (const BlockAddress *CE = dyn_cast<BlockAddress>(CPV)) {
388       Result = BlockAddress::get(
389                  cast<Function>(RemapOperand(CE->getFunction(), ValueMap)),
390                                  CE->getBasicBlock());
391     } else {
392       assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
393       llvm_unreachable("Unknown type of derived type constant value!");
394     }
395   } else if (isa<MetadataBase>(In)) {
396     Result = const_cast<Value*>(In);
397   } else if (isa<InlineAsm>(In)) {
398     Result = const_cast<Value*>(In);
399   }
400
401   // Cache the mapping in our local map structure
402   if (Result) {
403     ValueMap[In] = Result;
404     return Result;
405   }
406
407 #ifndef NDEBUG
408   dbgs() << "LinkModules ValueMap: \n";
409   PrintMap(ValueMap);
410
411   dbgs() << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
412   llvm_unreachable("Couldn't remap value!");
413 #endif
414   return 0;
415 }
416
417 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
418 /// in the symbol table.  This is good for all clients except for us.  Go
419 /// through the trouble to force this back.
420 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
421   assert(GV->getName() != Name && "Can't force rename to self");
422   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
423
424   // If there is a conflict, rename the conflict.
425   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
426     assert(ConflictGV->hasLocalLinkage() &&
427            "Not conflicting with a static global, should link instead!");
428     GV->takeName(ConflictGV);
429     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
430     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
431   } else {
432     GV->setName(Name);              // Force the name back
433   }
434 }
435
436 /// CopyGVAttributes - copy additional attributes (those not needed to construct
437 /// a GlobalValue) from the SrcGV to the DestGV.
438 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
439   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
440   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
441   DestGV->copyAttributesFrom(SrcGV);
442   DestGV->setAlignment(Alignment);
443 }
444
445 /// GetLinkageResult - This analyzes the two global values and determines what
446 /// the result will look like in the destination module.  In particular, it
447 /// computes the resultant linkage type, computes whether the global in the
448 /// source should be copied over to the destination (replacing the existing
449 /// one), and computes whether this linkage is an error or not. It also performs
450 /// visibility checks: we cannot link together two symbols with different
451 /// visibilities.
452 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
453                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
454                              std::string *Err) {
455   assert((!Dest || !Src->hasLocalLinkage()) &&
456          "If Src has internal linkage, Dest shouldn't be set!");
457   if (!Dest) {
458     // Linking something to nothing.
459     LinkFromSrc = true;
460     LT = Src->getLinkage();
461   } else if (Src->isDeclaration()) {
462     // If Src is external or if both Src & Dest are external..  Just link the
463     // external globals, we aren't adding anything.
464     if (Src->hasDLLImportLinkage()) {
465       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
466       if (Dest->isDeclaration()) {
467         LinkFromSrc = true;
468         LT = Src->getLinkage();
469       }
470     } else if (Dest->hasExternalWeakLinkage()) {
471       // If the Dest is weak, use the source linkage.
472       LinkFromSrc = true;
473       LT = Src->getLinkage();
474     } else {
475       LinkFromSrc = false;
476       LT = Dest->getLinkage();
477     }
478   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
479     // If Dest is external but Src is not:
480     LinkFromSrc = true;
481     LT = Src->getLinkage();
482   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
483     if (Src->getLinkage() != Dest->getLinkage())
484       return Error(Err, "Linking globals named '" + Src->getName() +
485             "': can only link appending global with another appending global!");
486     LinkFromSrc = true; // Special cased.
487     LT = Src->getLinkage();
488   } else if (Src->isWeakForLinker()) {
489     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
490     // or DLL* linkage.
491     if (Dest->hasExternalWeakLinkage() ||
492         Dest->hasAvailableExternallyLinkage() ||
493         (Dest->hasLinkOnceLinkage() &&
494          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
495       LinkFromSrc = true;
496       LT = Src->getLinkage();
497     } else {
498       LinkFromSrc = false;
499       LT = Dest->getLinkage();
500     }
501   } else if (Dest->isWeakForLinker()) {
502     // At this point we know that Src has External* or DLL* linkage.
503     if (Src->hasExternalWeakLinkage()) {
504       LinkFromSrc = false;
505       LT = Dest->getLinkage();
506     } else {
507       LinkFromSrc = true;
508       LT = GlobalValue::ExternalLinkage;
509     }
510   } else {
511     assert((Dest->hasExternalLinkage() ||
512             Dest->hasDLLImportLinkage() ||
513             Dest->hasDLLExportLinkage() ||
514             Dest->hasExternalWeakLinkage()) &&
515            (Src->hasExternalLinkage() ||
516             Src->hasDLLImportLinkage() ||
517             Src->hasDLLExportLinkage() ||
518             Src->hasExternalWeakLinkage()) &&
519            "Unexpected linkage type!");
520     return Error(Err, "Linking globals named '" + Src->getName() +
521                  "': symbol multiply defined!");
522   }
523
524   // Check visibility
525   if (Dest && Src->getVisibility() != Dest->getVisibility())
526     if (!Src->isDeclaration() && !Dest->isDeclaration())
527       return Error(Err, "Linking globals named '" + Src->getName() +
528                    "': symbols have different visibilities!");
529   return false;
530 }
531
532 // Insert all of the named mdnoes in Src into the Dest module.
533 static void LinkNamedMDNodes(Module *Dest, Module *Src) {
534   for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
535          E = Src->named_metadata_end(); I != E; ++I) {
536     const NamedMDNode *SrcNMD = I;
537     NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
538     if (!DestNMD)
539       NamedMDNode::Create(SrcNMD, Dest);
540     else {
541       // Add Src elements into Dest node.
542       for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i) 
543         DestNMD->addOperand(SrcNMD->getOperand(i));
544     }
545   }
546 }
547
548 // LinkGlobals - Loop through the global variables in the src module and merge
549 // them into the dest module.
550 static bool LinkGlobals(Module *Dest, const Module *Src,
551                         std::map<const Value*, Value*> &ValueMap,
552                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
553                         std::string *Err) {
554   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
555
556   // Loop over all of the globals in the src module, mapping them over as we go
557   for (Module::const_global_iterator I = Src->global_begin(),
558        E = Src->global_end(); I != E; ++I) {
559     const GlobalVariable *SGV = I;
560     GlobalValue *DGV = 0;
561
562     // Check to see if may have to link the global with the global, alias or
563     // function.
564     if (SGV->hasName() && !SGV->hasLocalLinkage())
565       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
566
567     // If we found a global with the same name in the dest module, but it has
568     // internal linkage, we are really not doing any linkage here.
569     if (DGV && DGV->hasLocalLinkage())
570       DGV = 0;
571
572     // If types don't agree due to opaque types, try to resolve them.
573     if (DGV && DGV->getType() != SGV->getType())
574       RecursiveResolveTypes(SGV->getType(), DGV->getType());
575
576     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
577             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
578            "Global must either be external or have an initializer!");
579
580     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
581     bool LinkFromSrc = false;
582     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
583       return true;
584
585     if (DGV == 0) {
586       // No linking to be performed, simply create an identical version of the
587       // symbol over in the dest module... the initializer will be filled in
588       // later by LinkGlobalInits.
589       GlobalVariable *NewDGV =
590         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
591                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
592                            SGV->getName(), 0, false,
593                            SGV->getType()->getAddressSpace());
594       // Propagate alignment, visibility and section info.
595       CopyGVAttributes(NewDGV, SGV);
596
597       // If the LLVM runtime renamed the global, but it is an externally visible
598       // symbol, DGV must be an existing global with internal linkage.  Rename
599       // it.
600       if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
601         ForceRenaming(NewDGV, SGV->getName());
602
603       // Make sure to remember this mapping.
604       ValueMap[SGV] = NewDGV;
605
606       // Keep track that this is an appending variable.
607       if (SGV->hasAppendingLinkage())
608         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
609       continue;
610     }
611
612     // If the visibilities of the symbols disagree and the destination is a
613     // prototype, take the visibility of its input.
614     if (DGV->isDeclaration())
615       DGV->setVisibility(SGV->getVisibility());
616
617     if (DGV->hasAppendingLinkage()) {
618       // No linking is performed yet.  Just insert a new copy of the global, and
619       // keep track of the fact that it is an appending variable in the
620       // AppendingVars map.  The name is cleared out so that no linkage is
621       // performed.
622       GlobalVariable *NewDGV =
623         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
624                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
625                            "", 0, false,
626                            SGV->getType()->getAddressSpace());
627
628       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
629       NewDGV->setAlignment(DGV->getAlignment());
630       // Propagate alignment, section and visibility info.
631       CopyGVAttributes(NewDGV, SGV);
632
633       // Make sure to remember this mapping...
634       ValueMap[SGV] = NewDGV;
635
636       // Keep track that this is an appending variable...
637       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
638       continue;
639     }
640
641     if (LinkFromSrc) {
642       if (isa<GlobalAlias>(DGV))
643         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
644                      "': symbol multiple defined");
645
646       // If the types don't match, and if we are to link from the source, nuke
647       // DGV and create a new one of the appropriate type.  Note that the thing
648       // we are replacing may be a function (if a prototype, weak, etc) or a
649       // global variable.
650       GlobalVariable *NewDGV =
651         new GlobalVariable(*Dest, SGV->getType()->getElementType(), 
652                            SGV->isConstant(), NewLinkage, /*init*/0, 
653                            DGV->getName(), 0, false,
654                            SGV->getType()->getAddressSpace());
655
656       // Propagate alignment, section, and visibility info.
657       CopyGVAttributes(NewDGV, SGV);
658       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, 
659                                                               DGV->getType()));
660
661       // DGV will conflict with NewDGV because they both had the same
662       // name. We must erase this now so ForceRenaming doesn't assert
663       // because DGV might not have internal linkage.
664       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
665         Var->eraseFromParent();
666       else
667         cast<Function>(DGV)->eraseFromParent();
668
669       // If the symbol table renamed the global, but it is an externally visible
670       // symbol, DGV must be an existing global with internal linkage.  Rename.
671       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
672         ForceRenaming(NewDGV, SGV->getName());
673
674       // Inherit const as appropriate.
675       NewDGV->setConstant(SGV->isConstant());
676
677       // Make sure to remember this mapping.
678       ValueMap[SGV] = NewDGV;
679       continue;
680     }
681
682     // Not "link from source", keep the one in the DestModule and remap the
683     // input onto it.
684
685     // Special case for const propagation.
686     if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
687       if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
688         DGVar->setConstant(true);
689
690     // SGV is global, but DGV is alias.
691     if (isa<GlobalAlias>(DGV)) {
692       // The only valid mappings are:
693       // - SGV is external declaration, which is effectively a no-op.
694       // - SGV is weak, when we just need to throw SGV out.
695       if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
696         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
697                      "': symbol multiple defined");
698     }
699
700     // Set calculated linkage
701     DGV->setLinkage(NewLinkage);
702
703     // Make sure to remember this mapping...
704     ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
705   }
706   return false;
707 }
708
709 static GlobalValue::LinkageTypes
710 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
711   GlobalValue::LinkageTypes SL = SGV->getLinkage();
712   GlobalValue::LinkageTypes DL = DGV->getLinkage();
713   if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
714     return GlobalValue::ExternalLinkage;
715   else if (SL == GlobalValue::WeakAnyLinkage ||
716            DL == GlobalValue::WeakAnyLinkage)
717     return GlobalValue::WeakAnyLinkage;
718   else if (SL == GlobalValue::WeakODRLinkage ||
719            DL == GlobalValue::WeakODRLinkage)
720     return GlobalValue::WeakODRLinkage;
721   else if (SL == GlobalValue::InternalLinkage &&
722            DL == GlobalValue::InternalLinkage)
723     return GlobalValue::InternalLinkage;
724   else if (SL == GlobalValue::LinkerPrivateLinkage &&
725            DL == GlobalValue::LinkerPrivateLinkage)
726     return GlobalValue::LinkerPrivateLinkage;
727   else {
728     assert (SL == GlobalValue::PrivateLinkage &&
729             DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
730     return GlobalValue::PrivateLinkage;
731   }
732 }
733
734 // LinkAlias - Loop through the alias in the src module and link them into the
735 // dest module. We're assuming, that all functions/global variables were already
736 // linked in.
737 static bool LinkAlias(Module *Dest, const Module *Src,
738                       std::map<const Value*, Value*> &ValueMap,
739                       std::string *Err) {
740   // Loop over all alias in the src module
741   for (Module::const_alias_iterator I = Src->alias_begin(),
742          E = Src->alias_end(); I != E; ++I) {
743     const GlobalAlias *SGA = I;
744     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
745     GlobalAlias *NewGA = NULL;
746
747     // Globals were already linked, thus we can just query ValueMap for variant
748     // of SAliasee in Dest.
749     std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
750     assert(VMI != ValueMap.end() && "Aliasee not linked");
751     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
752     GlobalValue* DGV = NULL;
753
754     // Try to find something 'similar' to SGA in destination module.
755     if (!DGV && !SGA->hasLocalLinkage()) {
756       DGV = Dest->getNamedAlias(SGA->getName());
757
758       // If types don't agree due to opaque types, try to resolve them.
759       if (DGV && DGV->getType() != SGA->getType())
760         RecursiveResolveTypes(SGA->getType(), DGV->getType());
761     }
762
763     if (!DGV && !SGA->hasLocalLinkage()) {
764       DGV = Dest->getGlobalVariable(SGA->getName());
765
766       // If types don't agree due to opaque types, try to resolve them.
767       if (DGV && DGV->getType() != SGA->getType())
768         RecursiveResolveTypes(SGA->getType(), DGV->getType());
769     }
770
771     if (!DGV && !SGA->hasLocalLinkage()) {
772       DGV = Dest->getFunction(SGA->getName());
773
774       // If types don't agree due to opaque types, try to resolve them.
775       if (DGV && DGV->getType() != SGA->getType())
776         RecursiveResolveTypes(SGA->getType(), DGV->getType());
777     }
778
779     // No linking to be performed on internal stuff.
780     if (DGV && DGV->hasLocalLinkage())
781       DGV = NULL;
782
783     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
784       // Types are known to be the same, check whether aliasees equal. As
785       // globals are already linked we just need query ValueMap to find the
786       // mapping.
787       if (DAliasee == DGA->getAliasedGlobal()) {
788         // This is just two copies of the same alias. Propagate linkage, if
789         // necessary.
790         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
791
792         NewGA = DGA;
793         // Proceed to 'common' steps
794       } else
795         return Error(Err, "Alias Collision on '"  + SGA->getName()+
796                      "': aliases have different aliasees");
797     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
798       // The only allowed way is to link alias with external declaration or weak
799       // symbol..
800       if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
801         // But only if aliasee is global too...
802         if (!isa<GlobalVariable>(DAliasee))
803           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
804                        "': aliasee is not global variable");
805
806         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
807                                 SGA->getName(), DAliasee, Dest);
808         CopyGVAttributes(NewGA, SGA);
809
810         // Any uses of DGV need to change to NewGA, with cast, if needed.
811         if (SGA->getType() != DGVar->getType())
812           DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
813                                                              DGVar->getType()));
814         else
815           DGVar->replaceAllUsesWith(NewGA);
816
817         // DGVar will conflict with NewGA because they both had the same
818         // name. We must erase this now so ForceRenaming doesn't assert
819         // because DGV might not have internal linkage.
820         DGVar->eraseFromParent();
821
822         // Proceed to 'common' steps
823       } else
824         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
825                      "': symbol multiple defined");
826     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
827       // The only allowed way is to link alias with external declaration or weak
828       // symbol...
829       if (DF->isDeclaration() || DF->isWeakForLinker()) {
830         // But only if aliasee is function too...
831         if (!isa<Function>(DAliasee))
832           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
833                        "': aliasee is not function");
834
835         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
836                                 SGA->getName(), DAliasee, Dest);
837         CopyGVAttributes(NewGA, SGA);
838
839         // Any uses of DF need to change to NewGA, with cast, if needed.
840         if (SGA->getType() != DF->getType())
841           DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
842                                                           DF->getType()));
843         else
844           DF->replaceAllUsesWith(NewGA);
845
846         // DF will conflict with NewGA because they both had the same
847         // name. We must erase this now so ForceRenaming doesn't assert
848         // because DF might not have internal linkage.
849         DF->eraseFromParent();
850
851         // Proceed to 'common' steps
852       } else
853         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
854                      "': symbol multiple defined");
855     } else {
856       // No linking to be performed, simply create an identical version of the
857       // alias over in the dest module...
858
859       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
860                               SGA->getName(), DAliasee, Dest);
861       CopyGVAttributes(NewGA, SGA);
862
863       // Proceed to 'common' steps
864     }
865
866     assert(NewGA && "No alias was created in destination module!");
867
868     // If the symbol table renamed the alias, but it is an externally visible
869     // symbol, DGA must be an global value with internal linkage. Rename it.
870     if (NewGA->getName() != SGA->getName() &&
871         !NewGA->hasLocalLinkage())
872       ForceRenaming(NewGA, SGA->getName());
873
874     // Remember this mapping so uses in the source module get remapped
875     // later by RemapOperand.
876     ValueMap[SGA] = NewGA;
877   }
878
879   return false;
880 }
881
882
883 // LinkGlobalInits - Update the initializers in the Dest module now that all
884 // globals that may be referenced are in Dest.
885 static bool LinkGlobalInits(Module *Dest, const Module *Src,
886                             std::map<const Value*, Value*> &ValueMap,
887                             std::string *Err) {
888   // Loop over all of the globals in the src module, mapping them over as we go
889   for (Module::const_global_iterator I = Src->global_begin(),
890        E = Src->global_end(); I != E; ++I) {
891     const GlobalVariable *SGV = I;
892
893     if (SGV->hasInitializer()) {      // Only process initialized GV's
894       // Figure out what the initializer looks like in the dest module...
895       Constant *SInit =
896         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
897       // Grab destination global variable or alias.
898       GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
899
900       // If dest if global variable, check that initializers match.
901       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
902         if (DGVar->hasInitializer()) {
903           if (SGV->hasExternalLinkage()) {
904             if (DGVar->getInitializer() != SInit)
905               return Error(Err, "Global Variable Collision on '" +
906                            SGV->getName() +
907                            "': global variables have different initializers");
908           } else if (DGVar->isWeakForLinker()) {
909             // Nothing is required, mapped values will take the new global
910             // automatically.
911           } else if (SGV->isWeakForLinker()) {
912             // Nothing is required, mapped values will take the new global
913             // automatically.
914           } else if (DGVar->hasAppendingLinkage()) {
915             llvm_unreachable("Appending linkage unimplemented!");
916           } else {
917             llvm_unreachable("Unknown linkage!");
918           }
919         } else {
920           // Copy the initializer over now...
921           DGVar->setInitializer(SInit);
922         }
923       } else {
924         // Destination is alias, the only valid situation is when source is
925         // weak. Also, note, that we already checked linkage in LinkGlobals(),
926         // thus we assert here.
927         // FIXME: Should we weaken this assumption, 'dereference' alias and
928         // check for initializer of aliasee?
929         assert(SGV->isWeakForLinker());
930       }
931     }
932   }
933   return false;
934 }
935
936 // LinkFunctionProtos - Link the functions together between the two modules,
937 // without doing function bodies... this just adds external function prototypes
938 // to the Dest function...
939 //
940 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
941                                std::map<const Value*, Value*> &ValueMap,
942                                std::string *Err) {
943   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
944
945   // Loop over all of the functions in the src module, mapping them over
946   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
947     const Function *SF = I;   // SrcFunction
948     GlobalValue *DGV = 0;
949
950     // Check to see if may have to link the function with the global, alias or
951     // function.
952     if (SF->hasName() && !SF->hasLocalLinkage())
953       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
954
955     // If we found a global with the same name in the dest module, but it has
956     // internal linkage, we are really not doing any linkage here.
957     if (DGV && DGV->hasLocalLinkage())
958       DGV = 0;
959
960     // If types don't agree due to opaque types, try to resolve them.
961     if (DGV && DGV->getType() != SF->getType())
962       RecursiveResolveTypes(SF->getType(), DGV->getType());
963
964     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
965     bool LinkFromSrc = false;
966     if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
967       return true;
968
969     // If there is no linkage to be performed, just bring over SF without
970     // modifying it.
971     if (DGV == 0) {
972       // Function does not already exist, simply insert an function signature
973       // identical to SF into the dest module.
974       Function *NewDF = Function::Create(SF->getFunctionType(),
975                                          SF->getLinkage(),
976                                          SF->getName(), Dest);
977       CopyGVAttributes(NewDF, SF);
978
979       // If the LLVM runtime renamed the function, but it is an externally
980       // visible symbol, DF must be an existing function with internal linkage.
981       // Rename it.
982       if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
983         ForceRenaming(NewDF, SF->getName());
984
985       // ... and remember this mapping...
986       ValueMap[SF] = NewDF;
987       continue;
988     }
989
990     // If the visibilities of the symbols disagree and the destination is a
991     // prototype, take the visibility of its input.
992     if (DGV->isDeclaration())
993       DGV->setVisibility(SF->getVisibility());
994
995     if (LinkFromSrc) {
996       if (isa<GlobalAlias>(DGV))
997         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
998                      "': symbol multiple defined");
999
1000       // We have a definition of the same name but different type in the
1001       // source module. Copy the prototype to the destination and replace
1002       // uses of the destination's prototype with the new prototype.
1003       Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
1004                                          SF->getName(), Dest);
1005       CopyGVAttributes(NewDF, SF);
1006
1007       // Any uses of DF need to change to NewDF, with cast
1008       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, 
1009                                                               DGV->getType()));
1010
1011       // DF will conflict with NewDF because they both had the same. We must
1012       // erase this now so ForceRenaming doesn't assert because DF might
1013       // not have internal linkage.
1014       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1015         Var->eraseFromParent();
1016       else
1017         cast<Function>(DGV)->eraseFromParent();
1018
1019       // If the symbol table renamed the function, but it is an externally
1020       // visible symbol, DF must be an existing function with internal
1021       // linkage.  Rename it.
1022       if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
1023         ForceRenaming(NewDF, SF->getName());
1024
1025       // Remember this mapping so uses in the source module get remapped
1026       // later by RemapOperand.
1027       ValueMap[SF] = NewDF;
1028       continue;
1029     }
1030
1031     // Not "link from source", keep the one in the DestModule and remap the
1032     // input onto it.
1033
1034     if (isa<GlobalAlias>(DGV)) {
1035       // The only valid mappings are:
1036       // - SF is external declaration, which is effectively a no-op.
1037       // - SF is weak, when we just need to throw SF out.
1038       if (!SF->isDeclaration() && !SF->isWeakForLinker())
1039         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1040                      "': symbol multiple defined");
1041     }
1042
1043     // Set calculated linkage
1044     DGV->setLinkage(NewLinkage);
1045
1046     // Make sure to remember this mapping.
1047     ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
1048   }
1049   return false;
1050 }
1051
1052 // LinkFunctionBody - Copy the source function over into the dest function and
1053 // fix up references to values.  At this point we know that Dest is an external
1054 // function, and that Src is not.
1055 static bool LinkFunctionBody(Function *Dest, Function *Src,
1056                              std::map<const Value*, Value*> &ValueMap,
1057                              std::string *Err) {
1058   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1059
1060   // Go through and convert function arguments over, remembering the mapping.
1061   Function::arg_iterator DI = Dest->arg_begin();
1062   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1063        I != E; ++I, ++DI) {
1064     DI->setName(I->getName());  // Copy the name information over...
1065
1066     // Add a mapping to our local map
1067     ValueMap[I] = DI;
1068   }
1069
1070   // Splice the body of the source function into the dest function.
1071   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1072
1073   // At this point, all of the instructions and values of the function are now
1074   // copied over.  The only problem is that they are still referencing values in
1075   // the Source function as operands.  Loop through all of the operands of the
1076   // functions and patch them up to point to the local versions...
1077   //
1078   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1079     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1080       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1081            OI != OE; ++OI)
1082         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1083           *OI = RemapOperand(*OI, ValueMap);
1084
1085   // There is no need to map the arguments anymore.
1086   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1087        I != E; ++I)
1088     ValueMap.erase(I);
1089
1090   return false;
1091 }
1092
1093
1094 // LinkFunctionBodies - Link in the function bodies that are defined in the
1095 // source module into the DestModule.  This consists basically of copying the
1096 // function over and fixing up references to values.
1097 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1098                                std::map<const Value*, Value*> &ValueMap,
1099                                std::string *Err) {
1100
1101   // Loop over all of the functions in the src module, mapping them over as we
1102   // go
1103   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1104     if (!SF->isDeclaration()) {               // No body if function is external
1105       Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1106
1107       // DF not external SF external?
1108       if (DF && DF->isDeclaration())
1109         // Only provide the function body if there isn't one already.
1110         if (LinkFunctionBody(DF, SF, ValueMap, Err))
1111           return true;
1112     }
1113   }
1114   return false;
1115 }
1116
1117 // LinkAppendingVars - If there were any appending global variables, link them
1118 // together now.  Return true on error.
1119 static bool LinkAppendingVars(Module *M,
1120                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
1121                               std::string *ErrorMsg) {
1122   if (AppendingVars.empty()) return false; // Nothing to do.
1123
1124   // Loop over the multimap of appending vars, processing any variables with the
1125   // same name, forming a new appending global variable with both of the
1126   // initializers merged together, then rewrite references to the old variables
1127   // and delete them.
1128   std::vector<Constant*> Inits;
1129   while (AppendingVars.size() > 1) {
1130     // Get the first two elements in the map...
1131     std::multimap<std::string,
1132       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1133
1134     // If the first two elements are for different names, there is no pair...
1135     // Otherwise there is a pair, so link them together...
1136     if (First->first == Second->first) {
1137       GlobalVariable *G1 = First->second, *G2 = Second->second;
1138       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1139       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1140
1141       // Check to see that they two arrays agree on type...
1142       if (T1->getElementType() != T2->getElementType())
1143         return Error(ErrorMsg,
1144          "Appending variables with different element types need to be linked!");
1145       if (G1->isConstant() != G2->isConstant())
1146         return Error(ErrorMsg,
1147                      "Appending variables linked with different const'ness!");
1148
1149       if (G1->getAlignment() != G2->getAlignment())
1150         return Error(ErrorMsg,
1151          "Appending variables with different alignment need to be linked!");
1152
1153       if (G1->getVisibility() != G2->getVisibility())
1154         return Error(ErrorMsg,
1155          "Appending variables with different visibility need to be linked!");
1156
1157       if (G1->getSection() != G2->getSection())
1158         return Error(ErrorMsg,
1159          "Appending variables with different section name need to be linked!");
1160
1161       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1162       ArrayType *NewType = ArrayType::get(T1->getElementType(), 
1163                                                          NewSize);
1164
1165       G1->setName("");   // Clear G1's name in case of a conflict!
1166
1167       // Create the new global variable...
1168       GlobalVariable *NG =
1169         new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1170                            /*init*/0, First->first, 0, G1->isThreadLocal(),
1171                            G1->getType()->getAddressSpace());
1172
1173       // Propagate alignment, visibility and section info.
1174       CopyGVAttributes(NG, G1);
1175
1176       // Merge the initializer...
1177       Inits.reserve(NewSize);
1178       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1179         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1180           Inits.push_back(I->getOperand(i));
1181       } else {
1182         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1183         Constant *CV = Constant::getNullValue(T1->getElementType());
1184         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1185           Inits.push_back(CV);
1186       }
1187       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1188         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1189           Inits.push_back(I->getOperand(i));
1190       } else {
1191         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1192         Constant *CV = Constant::getNullValue(T2->getElementType());
1193         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1194           Inits.push_back(CV);
1195       }
1196       NG->setInitializer(ConstantArray::get(NewType, Inits));
1197       Inits.clear();
1198
1199       // Replace any uses of the two global variables with uses of the new
1200       // global...
1201
1202       // FIXME: This should rewrite simple/straight-forward uses such as
1203       // getelementptr instructions to not use the Cast!
1204       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1205                              G1->getType()));
1206       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, 
1207                              G2->getType()));
1208
1209       // Remove the two globals from the module now...
1210       M->getGlobalList().erase(G1);
1211       M->getGlobalList().erase(G2);
1212
1213       // Put the new global into the AppendingVars map so that we can handle
1214       // linking of more than two vars...
1215       Second->second = NG;
1216     }
1217     AppendingVars.erase(First);
1218   }
1219
1220   return false;
1221 }
1222
1223 static bool ResolveAliases(Module *Dest) {
1224   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1225        I != E; ++I)
1226     if (const GlobalValue *GV = I->resolveAliasedGlobal())
1227       if (GV != I && !GV->isDeclaration())
1228         I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
1229
1230   return false;
1231 }
1232
1233 // LinkModules - This function links two modules together, with the resulting
1234 // left module modified to be the composite of the two input modules.  If an
1235 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1236 // the problem.  Upon failure, the Dest module could be in a modified state, and
1237 // shouldn't be relied on to be consistent.
1238 bool
1239 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1240   assert(Dest != 0 && "Invalid Destination module");
1241   assert(Src  != 0 && "Invalid Source Module");
1242
1243   if (Dest->getDataLayout().empty()) {
1244     if (!Src->getDataLayout().empty()) {
1245       Dest->setDataLayout(Src->getDataLayout());
1246     } else {
1247       std::string DataLayout;
1248
1249       if (Dest->getEndianness() == Module::AnyEndianness) {
1250         if (Src->getEndianness() == Module::BigEndian)
1251           DataLayout.append("E");
1252         else if (Src->getEndianness() == Module::LittleEndian)
1253           DataLayout.append("e");
1254       }
1255
1256       if (Dest->getPointerSize() == Module::AnyPointerSize) {
1257         if (Src->getPointerSize() == Module::Pointer64)
1258           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1259         else if (Src->getPointerSize() == Module::Pointer32)
1260           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1261       }
1262       Dest->setDataLayout(DataLayout);
1263     }
1264   }
1265
1266   // Copy the target triple from the source to dest if the dest's is empty.
1267   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1268     Dest->setTargetTriple(Src->getTargetTriple());
1269
1270   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1271       Src->getDataLayout() != Dest->getDataLayout())
1272     errs() << "WARNING: Linking two modules of different data layouts!\n";
1273   if (!Src->getTargetTriple().empty() &&
1274       Dest->getTargetTriple() != Src->getTargetTriple())
1275     errs() << "WARNING: Linking two modules of different target triples!\n";
1276
1277   // Append the module inline asm string.
1278   if (!Src->getModuleInlineAsm().empty()) {
1279     if (Dest->getModuleInlineAsm().empty())
1280       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1281     else
1282       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1283                                Src->getModuleInlineAsm());
1284   }
1285
1286   // Update the destination module's dependent libraries list with the libraries
1287   // from the source module. There's no opportunity for duplicates here as the
1288   // Module ensures that duplicate insertions are discarded.
1289   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1290        SI != SE; ++SI)
1291     Dest->addLibrary(*SI);
1292
1293   // LinkTypes - Go through the symbol table of the Src module and see if any
1294   // types are named in the src module that are not named in the Dst module.
1295   // Make sure there are no type name conflicts.
1296   if (LinkTypes(Dest, Src, ErrorMsg))
1297     return true;
1298
1299   // ValueMap - Mapping of values from what they used to be in Src, to what they
1300   // are now in Dest.
1301   std::map<const Value*, Value*> ValueMap;
1302
1303   // AppendingVars - Keep track of global variables in the destination module
1304   // with appending linkage.  After the module is linked together, they are
1305   // appended and the module is rewritten.
1306   std::multimap<std::string, GlobalVariable *> AppendingVars;
1307   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1308        I != E; ++I) {
1309     // Add all of the appending globals already in the Dest module to
1310     // AppendingVars.
1311     if (I->hasAppendingLinkage())
1312       AppendingVars.insert(std::make_pair(I->getName(), I));
1313   }
1314
1315   // Insert all of the named mdnoes in Src into the Dest module.
1316   LinkNamedMDNodes(Dest, Src);
1317
1318   // Insert all of the globals in src into the Dest module... without linking
1319   // initializers (which could refer to functions not yet mapped over).
1320   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1321     return true;
1322
1323   // Link the functions together between the two modules, without doing function
1324   // bodies... this just adds external function prototypes to the Dest
1325   // function...  We do this so that when we begin processing function bodies,
1326   // all of the global values that may be referenced are available in our
1327   // ValueMap.
1328   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1329     return true;
1330
1331   // If there were any alias, link them now. We really need to do this now,
1332   // because all of the aliases that may be referenced need to be available in
1333   // ValueMap
1334   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1335
1336   // Update the initializers in the Dest module now that all globals that may
1337   // be referenced are in Dest.
1338   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1339
1340   // Link in the function bodies that are defined in the source module into the
1341   // DestModule.  This consists basically of copying the function over and
1342   // fixing up references to values.
1343   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1344
1345   // If there were any appending global variables, link them together now.
1346   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1347
1348   // Resolve all uses of aliases with aliasees
1349   if (ResolveAliases(Dest)) return true;
1350
1351   // If the source library's module id is in the dependent library list of the
1352   // destination library, remove it since that module is now linked in.
1353   sys::Path modId;
1354   modId.set(Src->getModuleIdentifier());
1355   if (!modId.isEmpty())
1356     Dest->removeLibrary(modId.getBasename());
1357
1358   return false;
1359 }
1360
1361 // vim: sw=2