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