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