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