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