159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2361e513dSReid Spencer //
3361e513dSReid Spencer //                     The LLVM Compiler Infrastructure
4361e513dSReid Spencer //
5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source
6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details.
7361e513dSReid Spencer //
8361e513dSReid Spencer //===----------------------------------------------------------------------===//
9361e513dSReid Spencer //
10361e513dSReid Spencer // This file implements the LLVM module linker.
11361e513dSReid Spencer //
12361e513dSReid Spencer // Specifically, this:
13361e513dSReid Spencer //  * Merges global variables between the two modules
14361e513dSReid Spencer //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15361e513dSReid Spencer //  * Merges functions between two modules
16361e513dSReid Spencer //
17361e513dSReid Spencer //===----------------------------------------------------------------------===//
18361e513dSReid Spencer 
199b0ddbbeSReid Spencer #include "llvm/Linker.h"
20361e513dSReid Spencer #include "llvm/Constants.h"
21361e513dSReid Spencer #include "llvm/DerivedTypes.h"
22fac7b595SOwen Anderson #include "llvm/LLVMContext.h"
23361e513dSReid Spencer #include "llvm/Module.h"
2432af9e8cSReid Spencer #include "llvm/TypeSymbolTable.h"
253aaaa0b2SReid Spencer #include "llvm/ValueSymbolTable.h"
26361e513dSReid Spencer #include "llvm/Instructions.h"
27361e513dSReid Spencer #include "llvm/Assembly/Writer.h"
2856d06597STorok Edwin #include "llvm/Support/ErrorHandling.h"
29c521f541SChris Lattner #include "llvm/Support/raw_ostream.h"
30361e513dSReid Spencer #include "llvm/System/Path.h"
31eee6f995SChris Lattner #include "llvm/ADT/DenseMap.h"
3230c0f336SBill Wendling #include <sstream>
33361e513dSReid Spencer using namespace llvm;
34361e513dSReid Spencer 
35361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true.
36361e513dSReid Spencer // This just makes error return conditions a little bit simpler...
374975db62SDaniel Dunbar static inline bool Error(std::string *E, const Twine &Message) {
384975db62SDaniel Dunbar   if (E) *E = Message.str();
39361e513dSReid Spencer   return true;
40361e513dSReid Spencer }
41361e513dSReid Spencer 
42361e513dSReid Spencer // Function: ResolveTypes()
43361e513dSReid Spencer //
44361e513dSReid Spencer // Description:
45361e513dSReid Spencer //  Attempt to link the two specified types together.
46361e513dSReid Spencer //
47361e513dSReid Spencer // Inputs:
48361e513dSReid Spencer //  DestTy - The type to which we wish to resolve.
49361e513dSReid Spencer //  SrcTy  - The original type which we want to resolve.
50361e513dSReid Spencer //
51361e513dSReid Spencer // Outputs:
52361e513dSReid Spencer //  DestST - The symbol table in which the new type should be placed.
53361e513dSReid Spencer //
54361e513dSReid Spencer // Return value:
55361e513dSReid Spencer //  true  - There is an error and the types cannot yet be linked.
56361e513dSReid Spencer //  false - No errors.
57361e513dSReid Spencer //
588aa89e41SChris Lattner static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
59361e513dSReid Spencer   if (DestTy == SrcTy) return false;       // If already equal, noop
608aa89e41SChris Lattner   assert(DestTy && SrcTy && "Can't handle null types");
61361e513dSReid Spencer 
628aa89e41SChris Lattner   if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
638aa89e41SChris Lattner     // Type _is_ in module, just opaque...
648aa89e41SChris Lattner     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
658aa89e41SChris Lattner   } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
66361e513dSReid Spencer     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
67361e513dSReid Spencer   } else {
688aa89e41SChris Lattner     return true;  // Cannot link types... not-equal and neither is opaque.
69361e513dSReid Spencer   }
70361e513dSReid Spencer   return false;
71361e513dSReid Spencer }
72361e513dSReid Spencer 
73eee6f995SChris Lattner /// LinkerTypeMap - This implements a map of types that is stable
74eee6f995SChris Lattner /// even if types are resolved/refined to other types.  This is not a general
75eee6f995SChris Lattner /// purpose map, it is specific to the linker's use.
76eee6f995SChris Lattner namespace {
77eee6f995SChris Lattner class LinkerTypeMap : public AbstractTypeUser {
78eee6f995SChris Lattner   typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
79eee6f995SChris Lattner   TheMapTy TheMap;
80eee6f995SChris Lattner 
8156cdea6bSChris Lattner   LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
8256cdea6bSChris Lattner   void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
8356cdea6bSChris Lattner public:
8456cdea6bSChris Lattner   LinkerTypeMap() {}
8556cdea6bSChris Lattner   ~LinkerTypeMap() {
86eee6f995SChris Lattner     for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
87eee6f995SChris Lattner          E = TheMap.end(); I != E; ++I)
88eee6f995SChris Lattner       I->first->removeAbstractTypeUser(this);
89eee6f995SChris Lattner   }
90eee6f995SChris Lattner 
91eee6f995SChris Lattner   /// lookup - Return the value for the specified type or null if it doesn't
92eee6f995SChris Lattner   /// exist.
93eee6f995SChris Lattner   const Type *lookup(const Type *Ty) const {
94eee6f995SChris Lattner     TheMapTy::const_iterator I = TheMap.find(Ty);
95eee6f995SChris Lattner     if (I != TheMap.end()) return I->second;
96eee6f995SChris Lattner     return 0;
97eee6f995SChris Lattner   }
98eee6f995SChris Lattner 
99eee6f995SChris Lattner   /// erase - Remove the specified type, returning true if it was in the set.
100eee6f995SChris Lattner   bool erase(const Type *Ty) {
101eee6f995SChris Lattner     if (!TheMap.erase(Ty))
102eee6f995SChris Lattner       return false;
103eee6f995SChris Lattner     if (Ty->isAbstract())
104eee6f995SChris Lattner       Ty->removeAbstractTypeUser(this);
105eee6f995SChris Lattner     return true;
106eee6f995SChris Lattner   }
107eee6f995SChris Lattner 
108eee6f995SChris Lattner   /// insert - This returns true if the pointer was new to the set, false if it
109eee6f995SChris Lattner   /// was already in the set.
110eee6f995SChris Lattner   bool insert(const Type *Src, const Type *Dst) {
11138740a98SDan Gohman     if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
112eee6f995SChris Lattner       return false;  // Already in map.
113eee6f995SChris Lattner     if (Src->isAbstract())
114eee6f995SChris Lattner       Src->addAbstractTypeUser(this);
115eee6f995SChris Lattner     return true;
116eee6f995SChris Lattner   }
117eee6f995SChris Lattner 
118eee6f995SChris Lattner protected:
119eee6f995SChris Lattner   /// refineAbstractType - The callback method invoked when an abstract type is
120eee6f995SChris Lattner   /// resolved to another type.  An object must override this method to update
121eee6f995SChris Lattner   /// its internal state to reference NewType instead of OldType.
122eee6f995SChris Lattner   ///
123eee6f995SChris Lattner   virtual void refineAbstractType(const DerivedType *OldTy,
124eee6f995SChris Lattner                                   const Type *NewTy) {
125eee6f995SChris Lattner     TheMapTy::iterator I = TheMap.find(OldTy);
126eee6f995SChris Lattner     const Type *DstTy = I->second;
127eee6f995SChris Lattner 
128eee6f995SChris Lattner     TheMap.erase(I);
129eee6f995SChris Lattner     if (OldTy->isAbstract())
130eee6f995SChris Lattner       OldTy->removeAbstractTypeUser(this);
131eee6f995SChris Lattner 
132eee6f995SChris Lattner     // Don't reinsert into the map if the key is concrete now.
133eee6f995SChris Lattner     if (NewTy->isAbstract())
134eee6f995SChris Lattner       insert(NewTy, DstTy);
135eee6f995SChris Lattner   }
136eee6f995SChris Lattner 
137eee6f995SChris Lattner   /// The other case which AbstractTypeUsers must be aware of is when a type
138eee6f995SChris Lattner   /// makes the transition from being abstract (where it has clients on it's
139eee6f995SChris Lattner   /// AbstractTypeUsers list) to concrete (where it does not).  This method
140eee6f995SChris Lattner   /// notifies ATU's when this occurs for a type.
141eee6f995SChris Lattner   virtual void typeBecameConcrete(const DerivedType *AbsTy) {
142eee6f995SChris Lattner     TheMap.erase(AbsTy);
143eee6f995SChris Lattner     AbsTy->removeAbstractTypeUser(this);
144eee6f995SChris Lattner   }
145eee6f995SChris Lattner 
146eee6f995SChris Lattner   // for debugging...
147eee6f995SChris Lattner   virtual void dump() const {
148b25de3ffSChris Lattner     errs() << "AbstractTypeSet!\n";
149eee6f995SChris Lattner   }
150eee6f995SChris Lattner };
151eee6f995SChris Lattner }
152eee6f995SChris Lattner 
153eee6f995SChris Lattner 
154361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it
155361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types
156361e513dSReid Spencer // are compatible.
1579be15893SChris Lattner static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
158eee6f995SChris Lattner                                    LinkerTypeMap &Pointers) {
1599be15893SChris Lattner   if (DstTy == SrcTy) return false;       // If already equal, noop
160361e513dSReid Spencer 
161361e513dSReid Spencer   // If we found our opaque type, resolve it now!
1629be15893SChris Lattner   if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
1639be15893SChris Lattner     return ResolveTypes(DstTy, SrcTy);
164361e513dSReid Spencer 
165361e513dSReid Spencer   // Two types cannot be resolved together if they are of different primitive
166361e513dSReid Spencer   // type.  For example, we cannot resolve an int to a float.
1679be15893SChris Lattner   if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
168361e513dSReid Spencer 
169fe677e95SChris Lattner   // If neither type is abstract, then they really are just different types.
1709be15893SChris Lattner   if (!DstTy->isAbstract() && !SrcTy->isAbstract())
171fe677e95SChris Lattner     return true;
172fe677e95SChris Lattner 
173361e513dSReid Spencer   // Otherwise, resolve the used type used by this derived type...
1749be15893SChris Lattner   switch (DstTy->getTypeID()) {
1759995302bSChris Lattner   default:
1767a9c62baSReid Spencer     return true;
177361e513dSReid Spencer   case Type::FunctionTyID: {
1789be15893SChris Lattner     const FunctionType *DstFT = cast<FunctionType>(DstTy);
1799be15893SChris Lattner     const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
18085b66d18SChris Lattner     if (DstFT->isVarArg() != SrcFT->isVarArg() ||
18185b66d18SChris Lattner         DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
182361e513dSReid Spencer       return true;
1839be15893SChris Lattner 
1849be15893SChris Lattner     // Use TypeHolder's so recursive resolution won't break us.
1859be15893SChris Lattner     PATypeHolder ST(SrcFT), DT(DstFT);
1869be15893SChris Lattner     for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
1879be15893SChris Lattner       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
1889be15893SChris Lattner       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
189361e513dSReid Spencer         return true;
1909be15893SChris Lattner     }
191361e513dSReid Spencer     return false;
192361e513dSReid Spencer   }
193361e513dSReid Spencer   case Type::StructTyID: {
1949be15893SChris Lattner     const StructType *DstST = cast<StructType>(DstTy);
1959be15893SChris Lattner     const StructType *SrcST = cast<StructType>(SrcTy);
19685b66d18SChris Lattner     if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
1979995302bSChris Lattner       return true;
1989be15893SChris Lattner 
1999be15893SChris Lattner     PATypeHolder ST(SrcST), DT(DstST);
2009be15893SChris Lattner     for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
2019be15893SChris Lattner       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
2029be15893SChris Lattner       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
203361e513dSReid Spencer         return true;
2049be15893SChris Lattner     }
205361e513dSReid Spencer     return false;
206361e513dSReid Spencer   }
207361e513dSReid Spencer   case Type::ArrayTyID: {
2089be15893SChris Lattner     const ArrayType *DAT = cast<ArrayType>(DstTy);
2099be15893SChris Lattner     const ArrayType *SAT = cast<ArrayType>(SrcTy);
210361e513dSReid Spencer     if (DAT->getNumElements() != SAT->getNumElements()) return true;
211361e513dSReid Spencer     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
2128aa89e41SChris Lattner                                   Pointers);
213361e513dSReid Spencer   }
2149995302bSChris Lattner   case Type::VectorTyID: {
2159be15893SChris Lattner     const VectorType *DVT = cast<VectorType>(DstTy);
2169be15893SChris Lattner     const VectorType *SVT = cast<VectorType>(SrcTy);
2179995302bSChris Lattner     if (DVT->getNumElements() != SVT->getNumElements()) return true;
2189995302bSChris Lattner     return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
2199995302bSChris Lattner                                   Pointers);
2209995302bSChris Lattner   }
221361e513dSReid Spencer   case Type::PointerTyID: {
2229be15893SChris Lattner     const PointerType *DstPT = cast<PointerType>(DstTy);
2239be15893SChris Lattner     const PointerType *SrcPT = cast<PointerType>(SrcTy);
22485b66d18SChris Lattner 
22585b66d18SChris Lattner     if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
22685b66d18SChris Lattner       return true;
22785b66d18SChris Lattner 
228361e513dSReid Spencer     // If this is a pointer type, check to see if we have already seen it.  If
229361e513dSReid Spencer     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
230361e513dSReid Spencer     // an associative container for this search, because the type pointers (keys
231eee6f995SChris Lattner     // in the container) change whenever types get resolved.
232eee6f995SChris Lattner     if (SrcPT->isAbstract())
233eee6f995SChris Lattner       if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
234eee6f995SChris Lattner         return ExistingDestTy != DstPT;
235eee6f995SChris Lattner 
236eee6f995SChris Lattner     if (DstPT->isAbstract())
237eee6f995SChris Lattner       if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
238eee6f995SChris Lattner         return ExistingSrcTy != SrcPT;
239361e513dSReid Spencer     // Otherwise, add the current pointers to the vector to stop recursion on
240361e513dSReid Spencer     // this pair.
241eee6f995SChris Lattner     if (DstPT->isAbstract())
242eee6f995SChris Lattner       Pointers.insert(DstPT, SrcPT);
243eee6f995SChris Lattner     if (SrcPT->isAbstract())
244eee6f995SChris Lattner       Pointers.insert(SrcPT, DstPT);
2459be15893SChris Lattner 
24685b66d18SChris Lattner     return RecursiveResolveTypesI(DstPT->getElementType(),
24785b66d18SChris Lattner                                   SrcPT->getElementType(), Pointers);
248361e513dSReid Spencer   }
249361e513dSReid Spencer   }
250361e513dSReid Spencer }
251361e513dSReid Spencer 
2529be15893SChris Lattner static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
253eee6f995SChris Lattner   LinkerTypeMap PointerTypes;
2548aa89e41SChris Lattner   return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
255361e513dSReid Spencer }
256361e513dSReid Spencer 
257361e513dSReid Spencer 
258361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any
259361e513dSReid Spencer // types are named in the src module that are not named in the Dst module.
260361e513dSReid Spencer // Make sure there are no type name conflicts.
261361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
26232af9e8cSReid Spencer         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
26332af9e8cSReid Spencer   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
264361e513dSReid Spencer 
265361e513dSReid Spencer   // Look for a type plane for Type's...
26632af9e8cSReid Spencer   TypeSymbolTable::const_iterator TI = SrcST->begin();
26732af9e8cSReid Spencer   TypeSymbolTable::const_iterator TE = SrcST->end();
268361e513dSReid Spencer   if (TI == TE) return false;  // No named types, do nothing.
269361e513dSReid Spencer 
270361e513dSReid Spencer   // Some types cannot be resolved immediately because they depend on other
271361e513dSReid Spencer   // types being resolved to each other first.  This contains a list of types we
272361e513dSReid Spencer   // are waiting to recheck.
273361e513dSReid Spencer   std::vector<std::string> DelayedTypesToResolve;
274361e513dSReid Spencer 
275361e513dSReid Spencer   for ( ; TI != TE; ++TI ) {
276361e513dSReid Spencer     const std::string &Name = TI->first;
277361e513dSReid Spencer     const Type *RHS = TI->second;
278361e513dSReid Spencer 
2798aa89e41SChris Lattner     // Check to see if this type name is already in the dest module.
28032af9e8cSReid Spencer     Type *Entry = DestST->lookup(Name);
281361e513dSReid Spencer 
2828aa89e41SChris Lattner     // If the name is just in the source module, bring it over to the dest.
2838aa89e41SChris Lattner     if (Entry == 0) {
2848aa89e41SChris Lattner       if (!Name.empty())
285e9bb8552SChris Lattner         DestST->insert(Name, const_cast<Type*>(RHS));
2868aa89e41SChris Lattner     } else if (ResolveTypes(Entry, RHS)) {
287361e513dSReid Spencer       // They look different, save the types 'till later to resolve.
288361e513dSReid Spencer       DelayedTypesToResolve.push_back(Name);
289361e513dSReid Spencer     }
290361e513dSReid Spencer   }
291361e513dSReid Spencer 
292361e513dSReid Spencer   // Iteratively resolve types while we can...
293361e513dSReid Spencer   while (!DelayedTypesToResolve.empty()) {
294361e513dSReid Spencer     // Loop over all of the types, attempting to resolve them if possible...
295361e513dSReid Spencer     unsigned OldSize = DelayedTypesToResolve.size();
296361e513dSReid Spencer 
297361e513dSReid Spencer     // Try direct resolution by name...
298361e513dSReid Spencer     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
299361e513dSReid Spencer       const std::string &Name = DelayedTypesToResolve[i];
30032af9e8cSReid Spencer       Type *T1 = SrcST->lookup(Name);
30132af9e8cSReid Spencer       Type *T2 = DestST->lookup(Name);
3028aa89e41SChris Lattner       if (!ResolveTypes(T2, T1)) {
303361e513dSReid Spencer         // We are making progress!
304361e513dSReid Spencer         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
305361e513dSReid Spencer         --i;
306361e513dSReid Spencer       }
307361e513dSReid Spencer     }
308361e513dSReid Spencer 
309361e513dSReid Spencer     // Did we not eliminate any types?
310361e513dSReid Spencer     if (DelayedTypesToResolve.size() == OldSize) {
311361e513dSReid Spencer       // Attempt to resolve subelements of types.  This allows us to merge these
312361e513dSReid Spencer       // two types: { int* } and { opaque* }
313361e513dSReid Spencer       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
314361e513dSReid Spencer         const std::string &Name = DelayedTypesToResolve[i];
3159be15893SChris Lattner         if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
316361e513dSReid Spencer           // We are making progress!
317361e513dSReid Spencer           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
318361e513dSReid Spencer 
319361e513dSReid Spencer           // Go back to the main loop, perhaps we can resolve directly by name
320361e513dSReid Spencer           // now...
321361e513dSReid Spencer           break;
322361e513dSReid Spencer         }
323361e513dSReid Spencer       }
324361e513dSReid Spencer 
325361e513dSReid Spencer       // If we STILL cannot resolve the types, then there is something wrong.
326361e513dSReid Spencer       if (DelayedTypesToResolve.size() == OldSize) {
327361e513dSReid Spencer         // Remove the symbol name from the destination.
328361e513dSReid Spencer         DelayedTypesToResolve.pop_back();
329361e513dSReid Spencer       }
330361e513dSReid Spencer     }
331361e513dSReid Spencer   }
332361e513dSReid Spencer 
333361e513dSReid Spencer 
334361e513dSReid Spencer   return false;
335361e513dSReid Spencer }
336361e513dSReid Spencer 
337177a3008SChris Lattner #ifndef NDEBUG
338361e513dSReid Spencer static void PrintMap(const std::map<const Value*, Value*> &M) {
339361e513dSReid Spencer   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
340361e513dSReid Spencer        I != E; ++I) {
341b25de3ffSChris Lattner     errs() << " Fr: " << (void*)I->first << " ";
342361e513dSReid Spencer     I->first->dump();
343b25de3ffSChris Lattner     errs() << " To: " << (void*)I->second << " ";
344361e513dSReid Spencer     I->second->dump();
345b25de3ffSChris Lattner     errs() << "\n";
346361e513dSReid Spencer   }
347361e513dSReid Spencer }
348177a3008SChris Lattner #endif
349361e513dSReid Spencer 
350361e513dSReid Spencer 
351d3ba7d9bSReid Spencer // RemapOperand - Use ValueMap to convert constants from one module to another.
352361e513dSReid Spencer static Value *RemapOperand(const Value *In,
353fac7b595SOwen Anderson                            std::map<const Value*, Value*> &ValueMap,
354fac7b595SOwen Anderson                            LLVMContext &Context) {
3557391dde1SChris Lattner   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
3563aaaa0b2SReid Spencer   if (I != ValueMap.end())
3573aaaa0b2SReid Spencer     return I->second;
358361e513dSReid Spencer 
359d3ba7d9bSReid Spencer   // Check to see if it's a constant that we are interested in transforming.
360c7745926SChris Lattner   Value *Result = 0;
361361e513dSReid Spencer   if (const Constant *CPV = dyn_cast<Constant>(In)) {
362361e513dSReid Spencer     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
3637a9c62baSReid Spencer         isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
3647391dde1SChris Lattner       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
365361e513dSReid Spencer 
366361e513dSReid Spencer     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
367361e513dSReid Spencer       std::vector<Constant*> Operands(CPA->getNumOperands());
368361e513dSReid Spencer       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
369fac7b595SOwen Anderson         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap,
370fac7b595SOwen Anderson                                                  Context));
371fac7b595SOwen Anderson       Result =
372c2c7932cSOwen Anderson           ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
373361e513dSReid Spencer     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
374361e513dSReid Spencer       std::vector<Constant*> Operands(CPS->getNumOperands());
375361e513dSReid Spencer       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
376fac7b595SOwen Anderson         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap,
377fac7b595SOwen Anderson                                                  Context));
378fac7b595SOwen Anderson       Result =
37945308b57SOwen Anderson          ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
380361e513dSReid Spencer     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
381361e513dSReid Spencer       Result = const_cast<Constant*>(CPV);
382d84d35baSReid Spencer     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
38393bde9cbSChris Lattner       std::vector<Constant*> Operands(CP->getNumOperands());
38493bde9cbSChris Lattner       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
385fac7b595SOwen Anderson         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap,
386fac7b595SOwen Anderson                                      Context));
3874aa3295aSOwen Anderson       Result = ConstantVector::get(Operands);
388361e513dSReid Spencer     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
38919247f36SChris Lattner       std::vector<Constant*> Ops;
39019247f36SChris Lattner       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
391fac7b595SOwen Anderson         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap,
392fac7b595SOwen Anderson                                      Context)));
39319247f36SChris Lattner       Result = CE->getWithOperands(Ops);
394361e513dSReid Spencer     } else {
395177a3008SChris Lattner       assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
396fbcc663cSTorok Edwin       llvm_unreachable("Unknown type of derived type constant value!");
397361e513dSReid Spencer     }
398*794a40ddSDevang Patel   } else if (isa<MetadataBase>(In)) {
399*794a40ddSDevang Patel     Result = const_cast<Value*>(In);
400c7745926SChris Lattner   } else if (isa<InlineAsm>(In)) {
401c7745926SChris Lattner     Result = const_cast<Value*>(In);
402c7745926SChris Lattner   }
403361e513dSReid Spencer 
404d3ba7d9bSReid Spencer   // Cache the mapping in our local map structure
405c7745926SChris Lattner   if (Result) {
40666a6271cSAnton Korobeynikov     ValueMap[In] = Result;
407361e513dSReid Spencer     return Result;
408361e513dSReid Spencer   }
409361e513dSReid Spencer 
410177a3008SChris Lattner #ifndef NDEBUG
411b25de3ffSChris Lattner   errs() << "LinkModules ValueMap: \n";
4127391dde1SChris Lattner   PrintMap(ValueMap);
413361e513dSReid Spencer 
414b25de3ffSChris Lattner   errs() << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
415fbcc663cSTorok Edwin   llvm_unreachable("Couldn't remap value!");
416177a3008SChris Lattner #endif
417361e513dSReid Spencer   return 0;
418361e513dSReid Spencer }
419361e513dSReid Spencer 
42090246aa7SReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
42190246aa7SReid Spencer /// in the symbol table.  This is good for all clients except for us.  Go
42290246aa7SReid Spencer /// through the trouble to force this back.
423361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
424361e513dSReid Spencer   assert(GV->getName() != Name && "Can't force rename to self");
4253aaaa0b2SReid Spencer   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
426361e513dSReid Spencer 
427361e513dSReid Spencer   // If there is a conflict, rename the conflict.
4282a8d2e0eSChris Lattner   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
4296de96a1bSRafael Espindola     assert(ConflictGV->hasLocalLinkage() &&
43090246aa7SReid Spencer            "Not conflicting with a static global, should link instead!");
4312a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
432361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
4333aaaa0b2SReid Spencer     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
4342a8d2e0eSChris Lattner   } else {
4352a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
4363aaaa0b2SReid Spencer   }
4373aaaa0b2SReid Spencer }
4383aaaa0b2SReid Spencer 
4393aaaa0b2SReid Spencer /// CopyGVAttributes - copy additional attributes (those not needed to construct
4403aaaa0b2SReid Spencer /// a GlobalValue) from the SrcGV to the DestGV.
4413aaaa0b2SReid Spencer static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
442dd7daee8SDuncan Sands   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
443dd7daee8SDuncan Sands   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
444dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
445dd7daee8SDuncan Sands   DestGV->setAlignment(Alignment);
446361e513dSReid Spencer }
447361e513dSReid Spencer 
448fc61de39SChris Lattner /// GetLinkageResult - This analyzes the two global values and determines what
449fc61de39SChris Lattner /// the result will look like in the destination module.  In particular, it
450fc61de39SChris Lattner /// computes the resultant linkage type, computes whether the global in the
451fc61de39SChris Lattner /// source should be copied over to the destination (replacing the existing
45231fc4f95SAnton Korobeynikov /// one), and computes whether this linkage is an error or not. It also performs
45331fc4f95SAnton Korobeynikov /// visibility checks: we cannot link together two symbols with different
45431fc4f95SAnton Korobeynikov /// visibilities.
455f6439246SAnton Korobeynikov static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
456fc61de39SChris Lattner                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
457fc61de39SChris Lattner                              std::string *Err) {
4586de96a1bSRafael Espindola   assert((!Dest || !Src->hasLocalLinkage()) &&
459fc61de39SChris Lattner          "If Src has internal linkage, Dest shouldn't be set!");
460fc61de39SChris Lattner   if (!Dest) {
461fc61de39SChris Lattner     // Linking something to nothing.
462fc61de39SChris Lattner     LinkFromSrc = true;
463fc61de39SChris Lattner     LT = Src->getLinkage();
4645301e7c6SReid Spencer   } else if (Src->isDeclaration()) {
4651f93c50aSAnton Korobeynikov     // If Src is external or if both Src & Dest are external..  Just link the
466fc61de39SChris Lattner     // external globals, we aren't adding anything.
467d61d39ecSAnton Korobeynikov     if (Src->hasDLLImportLinkage()) {
46812c94949SAnton Korobeynikov       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
4695301e7c6SReid Spencer       if (Dest->isDeclaration()) {
470d61d39ecSAnton Korobeynikov         LinkFromSrc = true;
471d61d39ecSAnton Korobeynikov         LT = Src->getLinkage();
472d61d39ecSAnton Korobeynikov       }
473e06036d2SAndrew Lenharth     } else if (Dest->hasExternalWeakLinkage()) {
47412da8ce3SDuncan Sands       // If the Dest is weak, use the source linkage.
475e06036d2SAndrew Lenharth       LinkFromSrc = true;
476e06036d2SAndrew Lenharth       LT = Src->getLinkage();
477d61d39ecSAnton Korobeynikov     } else {
478fc61de39SChris Lattner       LinkFromSrc = false;
479fc61de39SChris Lattner       LT = Dest->getLinkage();
480d61d39ecSAnton Korobeynikov     }
4815301e7c6SReid Spencer   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
482fc61de39SChris Lattner     // If Dest is external but Src is not:
483fc61de39SChris Lattner     LinkFromSrc = true;
484fc61de39SChris Lattner     LT = Src->getLinkage();
485fc61de39SChris Lattner   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
486fc61de39SChris Lattner     if (Src->getLinkage() != Dest->getLinkage())
487fc61de39SChris Lattner       return Error(Err, "Linking globals named '" + Src->getName() +
488fc61de39SChris Lattner             "': can only link appending global with another appending global!");
489fc61de39SChris Lattner     LinkFromSrc = true; // Special cased.
490fc61de39SChris Lattner     LT = Src->getLinkage();
491d725c991SDuncan Sands   } else if (Src->isWeakForLinker()) {
492ce4396bcSDale Johannesen     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
493ce4396bcSDale Johannesen     // or DLL* linkage.
494184f1be4SChris Lattner     if (Dest->hasExternalWeakLinkage() ||
495184f1be4SChris Lattner         Dest->hasAvailableExternallyLinkage() ||
496184f1be4SChris Lattner         (Dest->hasLinkOnceLinkage() &&
497184f1be4SChris Lattner          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
498fc61de39SChris Lattner       LinkFromSrc = true;
499fc61de39SChris Lattner       LT = Src->getLinkage();
500fc61de39SChris Lattner     } else {
501fc61de39SChris Lattner       LinkFromSrc = false;
502fc61de39SChris Lattner       LT = Dest->getLinkage();
503fc61de39SChris Lattner     }
504d725c991SDuncan Sands   } else if (Dest->isWeakForLinker()) {
50512c94949SAnton Korobeynikov     // At this point we know that Src has External* or DLL* linkage.
50612c94949SAnton Korobeynikov     if (Src->hasExternalWeakLinkage()) {
50712c94949SAnton Korobeynikov       LinkFromSrc = false;
50812c94949SAnton Korobeynikov       LT = Dest->getLinkage();
50912c94949SAnton Korobeynikov     } else {
510fc61de39SChris Lattner       LinkFromSrc = true;
511fc61de39SChris Lattner       LT = GlobalValue::ExternalLinkage;
51212c94949SAnton Korobeynikov     }
513fc61de39SChris Lattner   } else {
514d61d39ecSAnton Korobeynikov     assert((Dest->hasExternalLinkage() ||
515d61d39ecSAnton Korobeynikov             Dest->hasDLLImportLinkage() ||
51612c94949SAnton Korobeynikov             Dest->hasDLLExportLinkage() ||
51712c94949SAnton Korobeynikov             Dest->hasExternalWeakLinkage()) &&
518d61d39ecSAnton Korobeynikov            (Src->hasExternalLinkage() ||
519d61d39ecSAnton Korobeynikov             Src->hasDLLImportLinkage() ||
52012c94949SAnton Korobeynikov             Src->hasDLLExportLinkage() ||
52112c94949SAnton Korobeynikov             Src->hasExternalWeakLinkage()) &&
522fc61de39SChris Lattner            "Unexpected linkage type!");
523fc61de39SChris Lattner     return Error(Err, "Linking globals named '" + Src->getName() +
524fc61de39SChris Lattner                  "': symbol multiply defined!");
525fc61de39SChris Lattner   }
52631fc4f95SAnton Korobeynikov 
52731fc4f95SAnton Korobeynikov   // Check visibility
52831fc4f95SAnton Korobeynikov   if (Dest && Src->getVisibility() != Dest->getVisibility())
5291cc79985SChris Lattner     if (!Src->isDeclaration() && !Dest->isDeclaration())
53031fc4f95SAnton Korobeynikov       return Error(Err, "Linking globals named '" + Src->getName() +
53131fc4f95SAnton Korobeynikov                    "': symbols have different visibilities!");
532fc61de39SChris Lattner   return false;
533fc61de39SChris Lattner }
534361e513dSReid Spencer 
5355c310be0SDevang Patel // Insert all of the named mdnoes in Src into the Dest module.
5365c310be0SDevang Patel static void LinkNamedMDNodes(Module *Dest, Module *Src) {
5375c310be0SDevang Patel   for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
5385c310be0SDevang Patel          E = Src->named_metadata_end(); I != E; ++I) {
5395c310be0SDevang Patel     const NamedMDNode *SrcNMD = I;
5405c310be0SDevang Patel     NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
5415c310be0SDevang Patel     if (!DestNMD)
5425c310be0SDevang Patel       NamedMDNode::Create(SrcNMD, Dest);
5435c310be0SDevang Patel     else {
5445c310be0SDevang Patel       // Add Src elements into Dest node.
5455c310be0SDevang Patel       for (unsigned i = 0, e = SrcNMD->getNumElements(); i != e; ++i)
5465c310be0SDevang Patel         DestNMD->addElement(SrcNMD->getElement(i));
5475c310be0SDevang Patel     }
5485c310be0SDevang Patel   }
5495c310be0SDevang Patel }
5505c310be0SDevang Patel 
551361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge
552361e513dSReid Spencer // them into the dest module.
553f6439246SAnton Korobeynikov static bool LinkGlobals(Module *Dest, const Module *Src,
554361e513dSReid Spencer                         std::map<const Value*, Value*> &ValueMap,
555361e513dSReid Spencer                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
556361e513dSReid Spencer                         std::string *Err) {
55734fc5a0eSChris Lattner   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
55834fc5a0eSChris Lattner 
559361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
560177a3008SChris Lattner   for (Module::const_global_iterator I = Src->global_begin(),
561177a3008SChris Lattner        E = Src->global_end(); I != E; ++I) {
562f6439246SAnton Korobeynikov     const GlobalVariable *SGV = I;
563e79f4c77SAnton Korobeynikov     GlobalValue *DGV = 0;
564e79f4c77SAnton Korobeynikov 
56534fc5a0eSChris Lattner     // Check to see if may have to link the global with the global, alias or
56634fc5a0eSChris Lattner     // function.
5676de96a1bSRafael Espindola     if (SGV->hasName() && !SGV->hasLocalLinkage())
568e03eecb7SDaniel Dunbar       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
569361e513dSReid Spencer 
570c08e7a00SChris Lattner     // If we found a global with the same name in the dest module, but it has
571c08e7a00SChris Lattner     // internal linkage, we are really not doing any linkage here.
5726de96a1bSRafael Espindola     if (DGV && DGV->hasLocalLinkage())
573c08e7a00SChris Lattner       DGV = 0;
574c08e7a00SChris Lattner 
575e79f4c77SAnton Korobeynikov     // If types don't agree due to opaque types, try to resolve them.
57634fc5a0eSChris Lattner     if (DGV && DGV->getType() != SGV->getType())
5778aa89e41SChris Lattner       RecursiveResolveTypes(SGV->getType(), DGV->getType());
578e79f4c77SAnton Korobeynikov 
5795e79a610SDan Gohman     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
5805e79a610SDan Gohman             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
581361e513dSReid Spencer            "Global must either be external or have an initializer!");
582361e513dSReid Spencer 
5831b9633d7SChris Lattner     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
5841b9633d7SChris Lattner     bool LinkFromSrc = false;
585fc61de39SChris Lattner     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
586fc61de39SChris Lattner       return true;
587361e513dSReid Spencer 
5880ead7a50SChris Lattner     if (DGV == 0) {
589361e513dSReid Spencer       // No linking to be performed, simply create an identical version of the
590361e513dSReid Spencer       // symbol over in the dest module... the initializer will be filled in
59134fc5a0eSChris Lattner       // later by LinkGlobalInits.
592361e513dSReid Spencer       GlobalVariable *NewDGV =
593b17f3294SOwen Anderson         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
594361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
595b17f3294SOwen Anderson                            SGV->getName(), 0, false,
596b32a9ef0SChris Lattner                            SGV->getType()->getAddressSpace());
5972dc36535SReid Spencer       // Propagate alignment, visibility and section info.
5983aaaa0b2SReid Spencer       CopyGVAttributes(NewDGV, SGV);
599dd924e4eSAndrew Lenharth 
600361e513dSReid Spencer       // If the LLVM runtime renamed the global, but it is an externally visible
601361e513dSReid Spencer       // symbol, DGV must be an existing global with internal linkage.  Rename
602361e513dSReid Spencer       // it.
6036de96a1bSRafael Espindola       if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
604361e513dSReid Spencer         ForceRenaming(NewDGV, SGV->getName());
605361e513dSReid Spencer 
6060ead7a50SChris Lattner       // Make sure to remember this mapping.
60766a6271cSAnton Korobeynikov       ValueMap[SGV] = NewDGV;
60866a6271cSAnton Korobeynikov 
60934fc5a0eSChris Lattner       // Keep track that this is an appending variable.
610361e513dSReid Spencer       if (SGV->hasAppendingLinkage())
611361e513dSReid Spencer         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
6120ead7a50SChris Lattner       continue;
6130ead7a50SChris Lattner     }
6140ead7a50SChris Lattner 
6150ead7a50SChris Lattner     // If the visibilities of the symbols disagree and the destination is a
6160ead7a50SChris Lattner     // prototype, take the visibility of its input.
6170ead7a50SChris Lattner     if (DGV->isDeclaration())
6180ead7a50SChris Lattner       DGV->setVisibility(SGV->getVisibility());
6190ead7a50SChris Lattner 
6200ead7a50SChris Lattner     if (DGV->hasAppendingLinkage()) {
621361e513dSReid Spencer       // No linking is performed yet.  Just insert a new copy of the global, and
622361e513dSReid Spencer       // keep track of the fact that it is an appending variable in the
623361e513dSReid Spencer       // AppendingVars map.  The name is cleared out so that no linkage is
624361e513dSReid Spencer       // performed.
625361e513dSReid Spencer       GlobalVariable *NewDGV =
626b17f3294SOwen Anderson         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
627361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
628b17f3294SOwen Anderson                            "", 0, false,
629b32a9ef0SChris Lattner                            SGV->getType()->getAddressSpace());
630361e513dSReid Spencer 
631e8a3e74bSAnton Korobeynikov       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
6323aaaa0b2SReid Spencer       NewDGV->setAlignment(DGV->getAlignment());
633e8a3e74bSAnton Korobeynikov       // Propagate alignment, section and visibility info.
6343aaaa0b2SReid Spencer       CopyGVAttributes(NewDGV, SGV);
635dd924e4eSAndrew Lenharth 
636361e513dSReid Spencer       // Make sure to remember this mapping...
63766a6271cSAnton Korobeynikov       ValueMap[SGV] = NewDGV;
638361e513dSReid Spencer 
639361e513dSReid Spencer       // Keep track that this is an appending variable...
640361e513dSReid Spencer       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
6410ead7a50SChris Lattner       continue;
6420ead7a50SChris Lattner     }
6430ead7a50SChris Lattner 
6440ead7a50SChris Lattner     if (LinkFromSrc) {
6450ead7a50SChris Lattner       if (isa<GlobalAlias>(DGV))
646eeb5ca6fSAnton Korobeynikov         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
647eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
648dd924e4eSAndrew Lenharth 
6490074ea3aSAnton Korobeynikov       // If the types don't match, and if we are to link from the source, nuke
65034fc5a0eSChris Lattner       // DGV and create a new one of the appropriate type.  Note that the thing
65134fc5a0eSChris Lattner       // we are replacing may be a function (if a prototype, weak, etc) or a
65234fc5a0eSChris Lattner       // global variable.
653fc61de39SChris Lattner       GlobalVariable *NewDGV =
654b17f3294SOwen Anderson         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
6555948fdf6SOwen Anderson                            SGV->isConstant(), NewLinkage, /*init*/0,
656b17f3294SOwen Anderson                            DGV->getName(), 0, false,
657b32a9ef0SChris Lattner                            SGV->getType()->getAddressSpace());
65834fc5a0eSChris Lattner 
65934fc5a0eSChris Lattner       // Propagate alignment, section, and visibility info.
66034fc5a0eSChris Lattner       CopyGVAttributes(NewDGV, SGV);
661487375e9SOwen Anderson       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
662fac7b595SOwen Anderson                                                               DGV->getType()));
66334fc5a0eSChris Lattner 
66434fc5a0eSChris Lattner       // DGV will conflict with NewDGV because they both had the same
665f6439246SAnton Korobeynikov       // name. We must erase this now so ForceRenaming doesn't assert
666f6439246SAnton Korobeynikov       // because DGV might not have internal linkage.
66734fc5a0eSChris Lattner       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
66834fc5a0eSChris Lattner         Var->eraseFromParent();
66934fc5a0eSChris Lattner       else
67034fc5a0eSChris Lattner         cast<Function>(DGV)->eraseFromParent();
67134fc5a0eSChris Lattner       DGV = NewDGV;
672f6439246SAnton Korobeynikov 
67334fc5a0eSChris Lattner       // If the symbol table renamed the global, but it is an externally visible
67434fc5a0eSChris Lattner       // symbol, DGV must be an existing global with internal linkage.  Rename.
6756de96a1bSRafael Espindola       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
676f6439246SAnton Korobeynikov         ForceRenaming(NewDGV, SGV->getName());
677f6439246SAnton Korobeynikov 
6780ead7a50SChris Lattner       // Inherit const as appropriate.
67934fc5a0eSChris Lattner       NewDGV->setConstant(SGV->isConstant());
680fc61de39SChris Lattner 
6810ead7a50SChris Lattner       // Make sure to remember this mapping.
6820ead7a50SChris Lattner       ValueMap[SGV] = NewDGV;
6830ead7a50SChris Lattner       continue;
6840ead7a50SChris Lattner     }
685f6439246SAnton Korobeynikov 
68634fc5a0eSChris Lattner     // Not "link from source", keep the one in the DestModule and remap the
68734fc5a0eSChris Lattner     // input onto it.
68834fc5a0eSChris Lattner 
68934fc5a0eSChris Lattner     // Special case for const propagation.
69034fc5a0eSChris Lattner     if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
69134fc5a0eSChris Lattner       if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
69234fc5a0eSChris Lattner         DGVar->setConstant(true);
69334fc5a0eSChris Lattner 
694006659f0SAnton Korobeynikov     // SGV is global, but DGV is alias.
695006659f0SAnton Korobeynikov     if (isa<GlobalAlias>(DGV)) {
696006659f0SAnton Korobeynikov       // The only valid mappings are:
697006659f0SAnton Korobeynikov       // - SGV is external declaration, which is effectively a no-op.
698006659f0SAnton Korobeynikov       // - SGV is weak, when we just need to throw SGV out.
699d725c991SDuncan Sands       if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
7000ead7a50SChris Lattner         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
7010ead7a50SChris Lattner                      "': symbol multiple defined");
702006659f0SAnton Korobeynikov     }
7030ead7a50SChris Lattner 
70434fc5a0eSChris Lattner     // Set calculated linkage
70534fc5a0eSChris Lattner     DGV->setLinkage(NewLinkage);
70634fc5a0eSChris Lattner 
70734fc5a0eSChris Lattner     // Make sure to remember this mapping...
708487375e9SOwen Anderson     ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
709361e513dSReid Spencer   }
710361e513dSReid Spencer   return false;
711361e513dSReid Spencer }
712361e513dSReid Spencer 
713dac5fa94SAnton Korobeynikov static GlobalValue::LinkageTypes
714dac5fa94SAnton Korobeynikov CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
71512da8ce3SDuncan Sands   GlobalValue::LinkageTypes SL = SGV->getLinkage();
71612da8ce3SDuncan Sands   GlobalValue::LinkageTypes DL = DGV->getLinkage();
71712da8ce3SDuncan Sands   if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
718dac5fa94SAnton Korobeynikov     return GlobalValue::ExternalLinkage;
71912da8ce3SDuncan Sands   else if (SL == GlobalValue::WeakAnyLinkage ||
72012da8ce3SDuncan Sands            DL == GlobalValue::WeakAnyLinkage)
72112da8ce3SDuncan Sands     return GlobalValue::WeakAnyLinkage;
72212da8ce3SDuncan Sands   else if (SL == GlobalValue::WeakODRLinkage ||
72312da8ce3SDuncan Sands            DL == GlobalValue::WeakODRLinkage)
72412da8ce3SDuncan Sands     return GlobalValue::WeakODRLinkage;
72512da8ce3SDuncan Sands   else if (SL == GlobalValue::InternalLinkage &&
72612da8ce3SDuncan Sands            DL == GlobalValue::InternalLinkage)
727dac5fa94SAnton Korobeynikov     return GlobalValue::InternalLinkage;
728a3c6f6bfSBill Wendling   else if (SL == GlobalValue::LinkerPrivateLinkage &&
729a3c6f6bfSBill Wendling            DL == GlobalValue::LinkerPrivateLinkage)
730a3c6f6bfSBill Wendling     return GlobalValue::LinkerPrivateLinkage;
7316de96a1bSRafael Espindola   else {
73212da8ce3SDuncan Sands     assert (SL == GlobalValue::PrivateLinkage &&
73312da8ce3SDuncan Sands             DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
7346de96a1bSRafael Espindola     return GlobalValue::PrivateLinkage;
735dac5fa94SAnton Korobeynikov   }
736dac5fa94SAnton Korobeynikov }
737dac5fa94SAnton Korobeynikov 
738b00c9c0dSLauro Ramos Venancio // LinkAlias - Loop through the alias in the src module and link them into the
739dac5fa94SAnton Korobeynikov // dest module. We're assuming, that all functions/global variables were already
740dac5fa94SAnton Korobeynikov // linked in.
7412e13597fSAnton Korobeynikov static bool LinkAlias(Module *Dest, const Module *Src,
7422e13597fSAnton Korobeynikov                       std::map<const Value*, Value*> &ValueMap,
7432e13597fSAnton Korobeynikov                       std::string *Err) {
744b00c9c0dSLauro Ramos Venancio   // Loop over all alias in the src module
745b00c9c0dSLauro Ramos Venancio   for (Module::const_alias_iterator I = Src->alias_begin(),
746b00c9c0dSLauro Ramos Venancio          E = Src->alias_end(); I != E; ++I) {
747dac5fa94SAnton Korobeynikov     const GlobalAlias *SGA = I;
748dac5fa94SAnton Korobeynikov     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
749dac5fa94SAnton Korobeynikov     GlobalAlias *NewGA = NULL;
750b00c9c0dSLauro Ramos Venancio 
751dac5fa94SAnton Korobeynikov     // Globals were already linked, thus we can just query ValueMap for variant
752acbdaa24SAnton Korobeynikov     // of SAliasee in Dest.
753d48ed17dSTed Kremenek     std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
754d48ed17dSTed Kremenek     assert(VMI != ValueMap.end() && "Aliasee not linked");
755d48ed17dSTed Kremenek     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
756acbdaa24SAnton Korobeynikov     GlobalValue* DGV = NULL;
757b00c9c0dSLauro Ramos Venancio 
758dac5fa94SAnton Korobeynikov     // Try to find something 'similar' to SGA in destination module.
7596de96a1bSRafael Espindola     if (!DGV && !SGA->hasLocalLinkage()) {
760acbdaa24SAnton Korobeynikov       DGV = Dest->getNamedAlias(SGA->getName());
761acbdaa24SAnton Korobeynikov 
762dac5fa94SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
763acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
764683ed3d9SChris Lattner         RecursiveResolveTypes(SGA->getType(), DGV->getType());
765acbdaa24SAnton Korobeynikov     }
7662e13597fSAnton Korobeynikov 
7676de96a1bSRafael Espindola     if (!DGV && !SGA->hasLocalLinkage()) {
768acbdaa24SAnton Korobeynikov       DGV = Dest->getGlobalVariable(SGA->getName());
769acbdaa24SAnton Korobeynikov 
770acbdaa24SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
771acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
772683ed3d9SChris Lattner         RecursiveResolveTypes(SGA->getType(), DGV->getType());
773acbdaa24SAnton Korobeynikov     }
774acbdaa24SAnton Korobeynikov 
7756de96a1bSRafael Espindola     if (!DGV && !SGA->hasLocalLinkage()) {
776acbdaa24SAnton Korobeynikov       DGV = Dest->getFunction(SGA->getName());
777acbdaa24SAnton Korobeynikov 
778acbdaa24SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
779acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
780683ed3d9SChris Lattner         RecursiveResolveTypes(SGA->getType(), DGV->getType());
781acbdaa24SAnton Korobeynikov     }
782acbdaa24SAnton Korobeynikov 
783acbdaa24SAnton Korobeynikov     // No linking to be performed on internal stuff.
7846de96a1bSRafael Espindola     if (DGV && DGV->hasLocalLinkage())
785acbdaa24SAnton Korobeynikov       DGV = NULL;
786acbdaa24SAnton Korobeynikov 
787acbdaa24SAnton Korobeynikov     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
788acbdaa24SAnton Korobeynikov       // Types are known to be the same, check whether aliasees equal. As
789dac5fa94SAnton Korobeynikov       // globals are already linked we just need query ValueMap to find the
790dac5fa94SAnton Korobeynikov       // mapping.
791dac5fa94SAnton Korobeynikov       if (DAliasee == DGA->getAliasedGlobal()) {
792dac5fa94SAnton Korobeynikov         // This is just two copies of the same alias. Propagate linkage, if
793dac5fa94SAnton Korobeynikov         // necessary.
794dac5fa94SAnton Korobeynikov         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
795dac5fa94SAnton Korobeynikov 
796dac5fa94SAnton Korobeynikov         NewGA = DGA;
797dac5fa94SAnton Korobeynikov         // Proceed to 'common' steps
798dac5fa94SAnton Korobeynikov       } else
799eeb5ca6fSAnton Korobeynikov         return Error(Err, "Alias Collision on '"  + SGA->getName()+
800eeb5ca6fSAnton Korobeynikov                      "': aliases have different aliasees");
801acbdaa24SAnton Korobeynikov     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
8029cd0b50fSAnton Korobeynikov       // The only allowed way is to link alias with external declaration or weak
8039cd0b50fSAnton Korobeynikov       // symbol..
804d725c991SDuncan Sands       if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
805510fc32dSAnton Korobeynikov         // But only if aliasee is global too...
806510fc32dSAnton Korobeynikov         if (!isa<GlobalVariable>(DAliasee))
807510fc32dSAnton Korobeynikov           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
808510fc32dSAnton Korobeynikov                        "': aliasee is not global variable");
809510fc32dSAnton Korobeynikov 
810dac5fa94SAnton Korobeynikov         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
811dac5fa94SAnton Korobeynikov                                 SGA->getName(), DAliasee, Dest);
812dac5fa94SAnton Korobeynikov         CopyGVAttributes(NewGA, SGA);
813dac5fa94SAnton Korobeynikov 
814dac5fa94SAnton Korobeynikov         // Any uses of DGV need to change to NewGA, with cast, if needed.
815acbdaa24SAnton Korobeynikov         if (SGA->getType() != DGVar->getType())
816487375e9SOwen Anderson           DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
817acbdaa24SAnton Korobeynikov                                                              DGVar->getType()));
818dac5fa94SAnton Korobeynikov         else
819acbdaa24SAnton Korobeynikov           DGVar->replaceAllUsesWith(NewGA);
820dac5fa94SAnton Korobeynikov 
821acbdaa24SAnton Korobeynikov         // DGVar will conflict with NewGA because they both had the same
822dac5fa94SAnton Korobeynikov         // name. We must erase this now so ForceRenaming doesn't assert
823dac5fa94SAnton Korobeynikov         // because DGV might not have internal linkage.
824acbdaa24SAnton Korobeynikov         DGVar->eraseFromParent();
825dac5fa94SAnton Korobeynikov 
826dac5fa94SAnton Korobeynikov         // Proceed to 'common' steps
827dac5fa94SAnton Korobeynikov       } else
828eeb5ca6fSAnton Korobeynikov         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
829eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
830acbdaa24SAnton Korobeynikov     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
8319cd0b50fSAnton Korobeynikov       // The only allowed way is to link alias with external declaration or weak
8329cd0b50fSAnton Korobeynikov       // symbol...
833d725c991SDuncan Sands       if (DF->isDeclaration() || DF->isWeakForLinker()) {
834510fc32dSAnton Korobeynikov         // But only if aliasee is function too...
835510fc32dSAnton Korobeynikov         if (!isa<Function>(DAliasee))
836510fc32dSAnton Korobeynikov           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
837510fc32dSAnton Korobeynikov                        "': aliasee is not function");
838510fc32dSAnton Korobeynikov 
83924f65c3aSAnton Korobeynikov         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
84024f65c3aSAnton Korobeynikov                                 SGA->getName(), DAliasee, Dest);
84124f65c3aSAnton Korobeynikov         CopyGVAttributes(NewGA, SGA);
84224f65c3aSAnton Korobeynikov 
84324f65c3aSAnton Korobeynikov         // Any uses of DF need to change to NewGA, with cast, if needed.
84424f65c3aSAnton Korobeynikov         if (SGA->getType() != DF->getType())
845487375e9SOwen Anderson           DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
84624f65c3aSAnton Korobeynikov                                                           DF->getType()));
84724f65c3aSAnton Korobeynikov         else
84824f65c3aSAnton Korobeynikov           DF->replaceAllUsesWith(NewGA);
84924f65c3aSAnton Korobeynikov 
85024f65c3aSAnton Korobeynikov         // DF will conflict with NewGA because they both had the same
85124f65c3aSAnton Korobeynikov         // name. We must erase this now so ForceRenaming doesn't assert
85224f65c3aSAnton Korobeynikov         // because DF might not have internal linkage.
85324f65c3aSAnton Korobeynikov         DF->eraseFromParent();
85424f65c3aSAnton Korobeynikov 
85524f65c3aSAnton Korobeynikov         // Proceed to 'common' steps
85624f65c3aSAnton Korobeynikov       } else
857eeb5ca6fSAnton Korobeynikov         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
858eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
859dac5fa94SAnton Korobeynikov     } else {
860acbdaa24SAnton Korobeynikov       // No linking to be performed, simply create an identical version of the
861acbdaa24SAnton Korobeynikov       // alias over in the dest module...
862dac5fa94SAnton Korobeynikov 
863dac5fa94SAnton Korobeynikov       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
864dac5fa94SAnton Korobeynikov                               SGA->getName(), DAliasee, Dest);
865dac5fa94SAnton Korobeynikov       CopyGVAttributes(NewGA, SGA);
866dac5fa94SAnton Korobeynikov 
867dac5fa94SAnton Korobeynikov       // Proceed to 'common' steps
868b00c9c0dSLauro Ramos Venancio     }
869dac5fa94SAnton Korobeynikov 
870dac5fa94SAnton Korobeynikov     assert(NewGA && "No alias was created in destination module!");
871dac5fa94SAnton Korobeynikov 
872d5160da5SAnton Korobeynikov     // If the symbol table renamed the alias, but it is an externally visible
873acbdaa24SAnton Korobeynikov     // symbol, DGA must be an global value with internal linkage. Rename it.
874dac5fa94SAnton Korobeynikov     if (NewGA->getName() != SGA->getName() &&
8756de96a1bSRafael Espindola         !NewGA->hasLocalLinkage())
876dac5fa94SAnton Korobeynikov       ForceRenaming(NewGA, SGA->getName());
877dac5fa94SAnton Korobeynikov 
878dac5fa94SAnton Korobeynikov     // Remember this mapping so uses in the source module get remapped
879dac5fa94SAnton Korobeynikov     // later by RemapOperand.
88066a6271cSAnton Korobeynikov     ValueMap[SGA] = NewGA;
881dac5fa94SAnton Korobeynikov   }
882dac5fa94SAnton Korobeynikov 
883b00c9c0dSLauro Ramos Venancio   return false;
884b00c9c0dSLauro Ramos Venancio }
885b00c9c0dSLauro Ramos Venancio 
886361e513dSReid Spencer 
887361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all
888361e513dSReid Spencer // globals that may be referenced are in Dest.
889361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src,
890361e513dSReid Spencer                             std::map<const Value*, Value*> &ValueMap,
891361e513dSReid Spencer                             std::string *Err) {
892361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
89344ab8aefSChris Lattner   for (Module::const_global_iterator I = Src->global_begin(),
89444ab8aefSChris Lattner        E = Src->global_end(); I != E; ++I) {
895361e513dSReid Spencer     const GlobalVariable *SGV = I;
896361e513dSReid Spencer 
897361e513dSReid Spencer     if (SGV->hasInitializer()) {      // Only process initialized GV's
898361e513dSReid Spencer       // Figure out what the initializer looks like in the dest module...
899361e513dSReid Spencer       Constant *SInit =
900fac7b595SOwen Anderson         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap,
901fac7b595SOwen Anderson                        Dest->getContext()));
902006659f0SAnton Korobeynikov       // Grab destination global variable or alias.
903006659f0SAnton Korobeynikov       GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
904361e513dSReid Spencer 
905006659f0SAnton Korobeynikov       // If dest if global variable, check that initializers match.
906006659f0SAnton Korobeynikov       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
907006659f0SAnton Korobeynikov         if (DGVar->hasInitializer()) {
908361e513dSReid Spencer           if (SGV->hasExternalLinkage()) {
909006659f0SAnton Korobeynikov             if (DGVar->getInitializer() != SInit)
910006659f0SAnton Korobeynikov               return Error(Err, "Global Variable Collision on '" +
911006659f0SAnton Korobeynikov                            SGV->getName() +
912eeb5ca6fSAnton Korobeynikov                            "': global variables have different initializers");
913d725c991SDuncan Sands           } else if (DGVar->isWeakForLinker()) {
914361e513dSReid Spencer             // Nothing is required, mapped values will take the new global
915361e513dSReid Spencer             // automatically.
916d725c991SDuncan Sands           } else if (SGV->isWeakForLinker()) {
917361e513dSReid Spencer             // Nothing is required, mapped values will take the new global
918361e513dSReid Spencer             // automatically.
919006659f0SAnton Korobeynikov           } else if (DGVar->hasAppendingLinkage()) {
920fbcc663cSTorok Edwin             llvm_unreachable("Appending linkage unimplemented!");
921361e513dSReid Spencer           } else {
922fbcc663cSTorok Edwin             llvm_unreachable("Unknown linkage!");
923361e513dSReid Spencer           }
924361e513dSReid Spencer         } else {
925361e513dSReid Spencer           // Copy the initializer over now...
926006659f0SAnton Korobeynikov           DGVar->setInitializer(SInit);
927006659f0SAnton Korobeynikov         }
928006659f0SAnton Korobeynikov       } else {
929006659f0SAnton Korobeynikov         // Destination is alias, the only valid situation is when source is
930006659f0SAnton Korobeynikov         // weak. Also, note, that we already checked linkage in LinkGlobals(),
931006659f0SAnton Korobeynikov         // thus we assert here.
932006659f0SAnton Korobeynikov         // FIXME: Should we weaken this assumption, 'dereference' alias and
933006659f0SAnton Korobeynikov         // check for initializer of aliasee?
934d725c991SDuncan Sands         assert(SGV->isWeakForLinker());
935361e513dSReid Spencer       }
936361e513dSReid Spencer     }
937361e513dSReid Spencer   }
938361e513dSReid Spencer   return false;
939361e513dSReid Spencer }
940361e513dSReid Spencer 
941361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules,
942361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes
943361e513dSReid Spencer // to the Dest function...
944361e513dSReid Spencer //
945361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src,
946361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
947361e513dSReid Spencer                                std::string *Err) {
94834fc5a0eSChris Lattner   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
94934fc5a0eSChris Lattner 
950d3ba7d9bSReid Spencer   // Loop over all of the functions in the src module, mapping them over
951361e513dSReid Spencer   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
952361e513dSReid Spencer     const Function *SF = I;   // SrcFunction
9531bb56dedSAnton Korobeynikov     GlobalValue *DGV = 0;
954228a5f18SChris Lattner 
95534fc5a0eSChris Lattner     // Check to see if may have to link the function with the global, alias or
95634fc5a0eSChris Lattner     // function.
9576de96a1bSRafael Espindola     if (SF->hasName() && !SF->hasLocalLinkage())
958e03eecb7SDaniel Dunbar       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
959361e513dSReid Spencer 
960c08e7a00SChris Lattner     // If we found a global with the same name in the dest module, but it has
961c08e7a00SChris Lattner     // internal linkage, we are really not doing any linkage here.
9626de96a1bSRafael Espindola     if (DGV && DGV->hasLocalLinkage())
963c08e7a00SChris Lattner       DGV = 0;
964c08e7a00SChris Lattner 
9651bb56dedSAnton Korobeynikov     // If types don't agree due to opaque types, try to resolve them.
96634fc5a0eSChris Lattner     if (DGV && DGV->getType() != SF->getType())
9671bb56dedSAnton Korobeynikov       RecursiveResolveTypes(SF->getType(), DGV->getType());
9681bb56dedSAnton Korobeynikov 
9690ead7a50SChris Lattner     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
9700ead7a50SChris Lattner     bool LinkFromSrc = false;
9710ead7a50SChris Lattner     if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
9720ead7a50SChris Lattner       return true;
9730ead7a50SChris Lattner 
974228a5f18SChris Lattner     // If there is no linkage to be performed, just bring over SF without
975228a5f18SChris Lattner     // modifying it.
9761bb56dedSAnton Korobeynikov     if (DGV == 0) {
977228a5f18SChris Lattner       // Function does not already exist, simply insert an function signature
978228a5f18SChris Lattner       // identical to SF into the dest module.
979228a5f18SChris Lattner       Function *NewDF = Function::Create(SF->getFunctionType(),
980228a5f18SChris Lattner                                          SF->getLinkage(),
981228a5f18SChris Lattner                                          SF->getName(), Dest);
982228a5f18SChris Lattner       CopyGVAttributes(NewDF, SF);
983ec7441b3SChris Lattner 
984228a5f18SChris Lattner       // If the LLVM runtime renamed the function, but it is an externally
985228a5f18SChris Lattner       // visible symbol, DF must be an existing function with internal linkage.
986228a5f18SChris Lattner       // Rename it.
9876de96a1bSRafael Espindola       if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
988228a5f18SChris Lattner         ForceRenaming(NewDF, SF->getName());
989228a5f18SChris Lattner 
990228a5f18SChris Lattner       // ... and remember this mapping...
991228a5f18SChris Lattner       ValueMap[SF] = NewDF;
992228a5f18SChris Lattner       continue;
9930ead7a50SChris Lattner     }
9940ead7a50SChris Lattner 
9950ead7a50SChris Lattner     // If the visibilities of the symbols disagree and the destination is a
9960ead7a50SChris Lattner     // prototype, take the visibility of its input.
9970ead7a50SChris Lattner     if (DGV->isDeclaration())
9980ead7a50SChris Lattner       DGV->setVisibility(SF->getVisibility());
9990ead7a50SChris Lattner 
10000ead7a50SChris Lattner     if (LinkFromSrc) {
10010ead7a50SChris Lattner       if (isa<GlobalAlias>(DGV))
10021bb56dedSAnton Korobeynikov         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
10031bb56dedSAnton Korobeynikov                      "': symbol multiple defined");
10041bb56dedSAnton Korobeynikov 
10053aaaa0b2SReid Spencer       // We have a definition of the same name but different type in the
10063aaaa0b2SReid Spencer       // source module. Copy the prototype to the destination and replace
10073aaaa0b2SReid Spencer       // uses of the destination's prototype with the new prototype.
10080ead7a50SChris Lattner       Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
10093aaaa0b2SReid Spencer                                          SF->getName(), Dest);
10103aaaa0b2SReid Spencer       CopyGVAttributes(NewDF, SF);
10113aaaa0b2SReid Spencer 
10123aaaa0b2SReid Spencer       // Any uses of DF need to change to NewDF, with cast
1013487375e9SOwen Anderson       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
1014fac7b595SOwen Anderson                                                               DGV->getType()));
10153aaaa0b2SReid Spencer 
10163aaaa0b2SReid Spencer       // DF will conflict with NewDF because they both had the same. We must
10173aaaa0b2SReid Spencer       // erase this now so ForceRenaming doesn't assert because DF might
10183aaaa0b2SReid Spencer       // not have internal linkage.
10190ead7a50SChris Lattner       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
10200ead7a50SChris Lattner         Var->eraseFromParent();
10210ead7a50SChris Lattner       else
10220ead7a50SChris Lattner         cast<Function>(DGV)->eraseFromParent();
10233aaaa0b2SReid Spencer 
10243aaaa0b2SReid Spencer       // If the symbol table renamed the function, but it is an externally
10253aaaa0b2SReid Spencer       // visible symbol, DF must be an existing function with internal
10263aaaa0b2SReid Spencer       // linkage.  Rename it.
10276de96a1bSRafael Espindola       if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
10283aaaa0b2SReid Spencer         ForceRenaming(NewDF, SF->getName());
10293aaaa0b2SReid Spencer 
10303aaaa0b2SReid Spencer       // Remember this mapping so uses in the source module get remapped
10313aaaa0b2SReid Spencer       // later by RemapOperand.
10323aaaa0b2SReid Spencer       ValueMap[SF] = NewDF;
1033228a5f18SChris Lattner       continue;
1034228a5f18SChris Lattner     }
1035361e513dSReid Spencer 
10360ead7a50SChris Lattner     // Not "link from source", keep the one in the DestModule and remap the
10370ead7a50SChris Lattner     // input onto it.
10380ead7a50SChris Lattner 
10390ead7a50SChris Lattner     if (isa<GlobalAlias>(DGV)) {
10400ead7a50SChris Lattner       // The only valid mappings are:
10410ead7a50SChris Lattner       // - SF is external declaration, which is effectively a no-op.
10420ead7a50SChris Lattner       // - SF is weak, when we just need to throw SF out.
1043d725c991SDuncan Sands       if (!SF->isDeclaration() && !SF->isWeakForLinker())
10440ead7a50SChris Lattner         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
10450ead7a50SChris Lattner                      "': symbol multiple defined");
104677e8ac4dSChris Lattner     }
104777e8ac4dSChris Lattner 
10480ead7a50SChris Lattner     // Set calculated linkage
10490ead7a50SChris Lattner     DGV->setLinkage(NewLinkage);
105077e8ac4dSChris Lattner 
10510ead7a50SChris Lattner     // Make sure to remember this mapping.
1052487375e9SOwen Anderson     ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
1053361e513dSReid Spencer   }
1054361e513dSReid Spencer   return false;
1055361e513dSReid Spencer }
1056361e513dSReid Spencer 
1057361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and
1058361e513dSReid Spencer // fix up references to values.  At this point we know that Dest is an external
1059361e513dSReid Spencer // function, and that Src is not.
10602f0557d0SChris Lattner static bool LinkFunctionBody(Function *Dest, Function *Src,
10613aaaa0b2SReid Spencer                              std::map<const Value*, Value*> &ValueMap,
1062361e513dSReid Spencer                              std::string *Err) {
10635301e7c6SReid Spencer   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1064361e513dSReid Spencer 
10657391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1066531f9e92SChris Lattner   Function::arg_iterator DI = Dest->arg_begin();
1067531f9e92SChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1068361e513dSReid Spencer        I != E; ++I, ++DI) {
10697629b71dSOwen Anderson     DI->setName(I->getName());  // Copy the name information over...
1070361e513dSReid Spencer 
1071361e513dSReid Spencer     // Add a mapping to our local map
107266a6271cSAnton Korobeynikov     ValueMap[I] = DI;
1073361e513dSReid Spencer   }
1074361e513dSReid Spencer 
10752f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
10762f0557d0SChris Lattner   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1077361e513dSReid Spencer 
1078361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1079361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1080361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
1081361e513dSReid Spencer   // functions and patch them up to point to the local versions...
1082361e513dSReid Spencer   //
1083361e513dSReid Spencer   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1084361e513dSReid Spencer     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1085361e513dSReid Spencer       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1086361e513dSReid Spencer            OI != OE; ++OI)
10872f0557d0SChris Lattner         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
108847db941fSOwen Anderson           *OI = RemapOperand(*OI, ValueMap, Dest->getContext());
10897391dde1SChris Lattner 
10907391dde1SChris Lattner   // There is no need to map the arguments anymore.
109144ab8aefSChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
109244ab8aefSChris Lattner        I != E; ++I)
10933aaaa0b2SReid Spencer     ValueMap.erase(I);
1094361e513dSReid Spencer 
1095361e513dSReid Spencer   return false;
1096361e513dSReid Spencer }
1097361e513dSReid Spencer 
1098361e513dSReid Spencer 
1099361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the
1100361e513dSReid Spencer // source module into the DestModule.  This consists basically of copying the
1101361e513dSReid Spencer // function over and fixing up references to values.
11022f0557d0SChris Lattner static bool LinkFunctionBodies(Module *Dest, Module *Src,
1103361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
1104361e513dSReid Spencer                                std::string *Err) {
1105361e513dSReid Spencer 
110690246aa7SReid Spencer   // Loop over all of the functions in the src module, mapping them over as we
110790246aa7SReid Spencer   // go
11082f0557d0SChris Lattner   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
11095301e7c6SReid Spencer     if (!SF->isDeclaration()) {               // No body if function is external
1110d53bd2daSChris Lattner       Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1111361e513dSReid Spencer 
1112361e513dSReid Spencer       // DF not external SF external?
1113d53bd2daSChris Lattner       if (DF && DF->isDeclaration())
1114361e513dSReid Spencer         // Only provide the function body if there isn't one already.
1115361e513dSReid Spencer         if (LinkFunctionBody(DF, SF, ValueMap, Err))
1116361e513dSReid Spencer           return true;
111790246aa7SReid Spencer     }
1118361e513dSReid Spencer   }
1119361e513dSReid Spencer   return false;
1120361e513dSReid Spencer }
1121361e513dSReid Spencer 
1122361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them
1123361e513dSReid Spencer // together now.  Return true on error.
1124361e513dSReid Spencer static bool LinkAppendingVars(Module *M,
1125361e513dSReid Spencer                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
1126361e513dSReid Spencer                               std::string *ErrorMsg) {
1127361e513dSReid Spencer   if (AppendingVars.empty()) return false; // Nothing to do.
1128361e513dSReid Spencer 
1129361e513dSReid Spencer   // Loop over the multimap of appending vars, processing any variables with the
1130361e513dSReid Spencer   // same name, forming a new appending global variable with both of the
1131361e513dSReid Spencer   // initializers merged together, then rewrite references to the old variables
1132361e513dSReid Spencer   // and delete them.
1133361e513dSReid Spencer   std::vector<Constant*> Inits;
1134361e513dSReid Spencer   while (AppendingVars.size() > 1) {
1135361e513dSReid Spencer     // Get the first two elements in the map...
1136361e513dSReid Spencer     std::multimap<std::string,
1137361e513dSReid Spencer       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1138361e513dSReid Spencer 
1139361e513dSReid Spencer     // If the first two elements are for different names, there is no pair...
1140361e513dSReid Spencer     // Otherwise there is a pair, so link them together...
1141361e513dSReid Spencer     if (First->first == Second->first) {
1142361e513dSReid Spencer       GlobalVariable *G1 = First->second, *G2 = Second->second;
1143361e513dSReid Spencer       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1144361e513dSReid Spencer       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1145361e513dSReid Spencer 
1146361e513dSReid Spencer       // Check to see that they two arrays agree on type...
1147361e513dSReid Spencer       if (T1->getElementType() != T2->getElementType())
1148361e513dSReid Spencer         return Error(ErrorMsg,
1149361e513dSReid Spencer          "Appending variables with different element types need to be linked!");
1150361e513dSReid Spencer       if (G1->isConstant() != G2->isConstant())
1151361e513dSReid Spencer         return Error(ErrorMsg,
1152361e513dSReid Spencer                      "Appending variables linked with different const'ness!");
1153361e513dSReid Spencer 
115485703e37SLauro Ramos Venancio       if (G1->getAlignment() != G2->getAlignment())
115585703e37SLauro Ramos Venancio         return Error(ErrorMsg,
115685703e37SLauro Ramos Venancio          "Appending variables with different alignment need to be linked!");
115785703e37SLauro Ramos Venancio 
115885703e37SLauro Ramos Venancio       if (G1->getVisibility() != G2->getVisibility())
115985703e37SLauro Ramos Venancio         return Error(ErrorMsg,
116085703e37SLauro Ramos Venancio          "Appending variables with different visibility need to be linked!");
116185703e37SLauro Ramos Venancio 
116285703e37SLauro Ramos Venancio       if (G1->getSection() != G2->getSection())
116385703e37SLauro Ramos Venancio         return Error(ErrorMsg,
116485703e37SLauro Ramos Venancio          "Appending variables with different section name need to be linked!");
116585703e37SLauro Ramos Venancio 
1166361e513dSReid Spencer       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
11674056ca95SOwen Anderson       ArrayType *NewType = ArrayType::get(T1->getElementType(),
1168fac7b595SOwen Anderson                                                          NewSize);
1169361e513dSReid Spencer 
1170d490d4f0SChris Lattner       G1->setName("");   // Clear G1's name in case of a conflict!
1171d490d4f0SChris Lattner 
1172361e513dSReid Spencer       // Create the new global variable...
1173361e513dSReid Spencer       GlobalVariable *NG =
1174b17f3294SOwen Anderson         new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1175b17f3294SOwen Anderson                            /*init*/0, First->first, 0, G1->isThreadLocal(),
1176b32a9ef0SChris Lattner                            G1->getType()->getAddressSpace());
1177361e513dSReid Spencer 
117885703e37SLauro Ramos Venancio       // Propagate alignment, visibility and section info.
117985703e37SLauro Ramos Venancio       CopyGVAttributes(NG, G1);
118085703e37SLauro Ramos Venancio 
1181361e513dSReid Spencer       // Merge the initializer...
1182361e513dSReid Spencer       Inits.reserve(NewSize);
1183361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1184361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1185361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
1186361e513dSReid Spencer       } else {
1187361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
11885a1acd99SOwen Anderson         Constant *CV = Constant::getNullValue(T1->getElementType());
1189361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1190361e513dSReid Spencer           Inits.push_back(CV);
1191361e513dSReid Spencer       }
1192361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1193361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1194361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
1195361e513dSReid Spencer       } else {
1196361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
11975a1acd99SOwen Anderson         Constant *CV = Constant::getNullValue(T2->getElementType());
1198361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1199361e513dSReid Spencer           Inits.push_back(CV);
1200361e513dSReid Spencer       }
1201c2c7932cSOwen Anderson       NG->setInitializer(ConstantArray::get(NewType, Inits));
1202361e513dSReid Spencer       Inits.clear();
1203361e513dSReid Spencer 
1204361e513dSReid Spencer       // Replace any uses of the two global variables with uses of the new
1205361e513dSReid Spencer       // global...
1206361e513dSReid Spencer 
1207361e513dSReid Spencer       // FIXME: This should rewrite simple/straight-forward uses such as
1208361e513dSReid Spencer       // getelementptr instructions to not use the Cast!
1209487375e9SOwen Anderson       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1210fac7b595SOwen Anderson                              G1->getType()));
1211487375e9SOwen Anderson       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1212fac7b595SOwen Anderson                              G2->getType()));
1213361e513dSReid Spencer 
1214361e513dSReid Spencer       // Remove the two globals from the module now...
1215361e513dSReid Spencer       M->getGlobalList().erase(G1);
1216361e513dSReid Spencer       M->getGlobalList().erase(G2);
1217361e513dSReid Spencer 
1218361e513dSReid Spencer       // Put the new global into the AppendingVars map so that we can handle
1219361e513dSReid Spencer       // linking of more than two vars...
1220361e513dSReid Spencer       Second->second = NG;
1221361e513dSReid Spencer     }
1222361e513dSReid Spencer     AppendingVars.erase(First);
1223361e513dSReid Spencer   }
1224361e513dSReid Spencer 
1225361e513dSReid Spencer   return false;
1226361e513dSReid Spencer }
1227361e513dSReid Spencer 
12282609888fSAnton Korobeynikov static bool ResolveAliases(Module *Dest) {
12292609888fSAnton Korobeynikov   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1230e6d90f5aSAnton Korobeynikov        I != E; ++I)
12311a114042SAnton Korobeynikov     if (const GlobalValue *GV = I->resolveAliasedGlobal())
1232ac2c6558SAnton Korobeynikov       if (GV != I && !GV->isDeclaration())
1233e6d90f5aSAnton Korobeynikov         I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
12342609888fSAnton Korobeynikov 
12352609888fSAnton Korobeynikov   return false;
12362609888fSAnton Korobeynikov }
1237361e513dSReid Spencer 
1238361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting
1239361e513dSReid Spencer // left module modified to be the composite of the two input modules.  If an
1240361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1241361e513dSReid Spencer // the problem.  Upon failure, the Dest module could be in a modified state, and
1242361e513dSReid Spencer // shouldn't be relied on to be consistent.
1243c4e31534SReid Spencer bool
1244c4e31534SReid Spencer Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1245361e513dSReid Spencer   assert(Dest != 0 && "Invalid Destination module");
1246361e513dSReid Spencer   assert(Src  != 0 && "Invalid Source Module");
1247361e513dSReid Spencer 
12487f3bd82aSChris Lattner   if (Dest->getDataLayout().empty()) {
12497f3bd82aSChris Lattner     if (!Src->getDataLayout().empty()) {
125078bddc38SChris Lattner       Dest->setDataLayout(Src->getDataLayout());
12517f3bd82aSChris Lattner     } else {
12523ac38e99SReid Spencer       std::string DataLayout;
12533ac38e99SReid Spencer 
1254bddf51bcSAnton Korobeynikov       if (Dest->getEndianness() == Module::AnyEndianness) {
12553ac38e99SReid Spencer         if (Src->getEndianness() == Module::BigEndian)
12563ac38e99SReid Spencer           DataLayout.append("E");
12573ac38e99SReid Spencer         else if (Src->getEndianness() == Module::LittleEndian)
12583ac38e99SReid Spencer           DataLayout.append("e");
1259bddf51bcSAnton Korobeynikov       }
1260bddf51bcSAnton Korobeynikov 
1261bddf51bcSAnton Korobeynikov       if (Dest->getPointerSize() == Module::AnyPointerSize) {
12623ac38e99SReid Spencer         if (Src->getPointerSize() == Module::Pointer64)
12633ac38e99SReid Spencer           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
12643ac38e99SReid Spencer         else if (Src->getPointerSize() == Module::Pointer32)
12653ac38e99SReid Spencer           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1266bddf51bcSAnton Korobeynikov       }
12673ac38e99SReid Spencer       Dest->setDataLayout(DataLayout);
12687f3bd82aSChris Lattner     }
12697f3bd82aSChris Lattner   }
1270361e513dSReid Spencer 
127190c2df5bSChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
12727f3bd82aSChris Lattner   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
12737f3bd82aSChris Lattner     Dest->setTargetTriple(Src->getTargetTriple());
12747f3bd82aSChris Lattner 
12757f3bd82aSChris Lattner   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
12767f3bd82aSChris Lattner       Src->getDataLayout() != Dest->getDataLayout())
1277b25de3ffSChris Lattner     errs() << "WARNING: Linking two modules of different data layouts!\n";
1278b7f5916eSChris Lattner   if (!Src->getTargetTriple().empty() &&
1279b7f5916eSChris Lattner       Dest->getTargetTriple() != Src->getTargetTriple())
1280b25de3ffSChris Lattner     errs() << "WARNING: Linking two modules of different target triples!\n";
1281361e513dSReid Spencer 
128290c2df5bSChris Lattner   // Append the module inline asm string.
12838ebd2164SChris Lattner   if (!Src->getModuleInlineAsm().empty()) {
12848ebd2164SChris Lattner     if (Dest->getModuleInlineAsm().empty())
12858ebd2164SChris Lattner       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1286dd2d3fafSChris Lattner     else
12878ebd2164SChris Lattner       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
12888ebd2164SChris Lattner                                Src->getModuleInlineAsm());
1289dd2d3fafSChris Lattner   }
1290dd2d3fafSChris Lattner 
1291361e513dSReid Spencer   // Update the destination module's dependent libraries list with the libraries
1292361e513dSReid Spencer   // from the source module. There's no opportunity for duplicates here as the
1293361e513dSReid Spencer   // Module ensures that duplicate insertions are discarded.
129490c2df5bSChris Lattner   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
129590c2df5bSChris Lattner        SI != SE; ++SI)
1296361e513dSReid Spencer     Dest->addLibrary(*SI);
1297361e513dSReid Spencer 
1298361e513dSReid Spencer   // LinkTypes - Go through the symbol table of the Src module and see if any
1299361e513dSReid Spencer   // types are named in the src module that are not named in the Dst module.
1300361e513dSReid Spencer   // Make sure there are no type name conflicts.
1301d3ba7d9bSReid Spencer   if (LinkTypes(Dest, Src, ErrorMsg))
1302d3ba7d9bSReid Spencer     return true;
1303361e513dSReid Spencer 
1304361e513dSReid Spencer   // ValueMap - Mapping of values from what they used to be in Src, to what they
1305361e513dSReid Spencer   // are now in Dest.
1306361e513dSReid Spencer   std::map<const Value*, Value*> ValueMap;
1307361e513dSReid Spencer 
1308361e513dSReid Spencer   // AppendingVars - Keep track of global variables in the destination module
1309361e513dSReid Spencer   // with appending linkage.  After the module is linked together, they are
1310361e513dSReid Spencer   // appended and the module is rewritten.
1311361e513dSReid Spencer   std::multimap<std::string, GlobalVariable *> AppendingVars;
131244ab8aefSChris Lattner   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
131344ab8aefSChris Lattner        I != E; ++I) {
1314361e513dSReid Spencer     // Add all of the appending globals already in the Dest module to
1315361e513dSReid Spencer     // AppendingVars.
1316361e513dSReid Spencer     if (I->hasAppendingLinkage())
1317361e513dSReid Spencer       AppendingVars.insert(std::make_pair(I->getName(), I));
1318361e513dSReid Spencer   }
1319361e513dSReid Spencer 
13205c310be0SDevang Patel   // Insert all of the named mdnoes in Src into the Dest module.
13215c310be0SDevang Patel   LinkNamedMDNodes(Dest, Src);
13225c310be0SDevang Patel 
1323361e513dSReid Spencer   // Insert all of the globals in src into the Dest module... without linking
1324361e513dSReid Spencer   // initializers (which could refer to functions not yet mapped over).
13253aaaa0b2SReid Spencer   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1326361e513dSReid Spencer     return true;
1327361e513dSReid Spencer 
1328361e513dSReid Spencer   // Link the functions together between the two modules, without doing function
1329361e513dSReid Spencer   // bodies... this just adds external function prototypes to the Dest
1330361e513dSReid Spencer   // function...  We do this so that when we begin processing function bodies,
1331361e513dSReid Spencer   // all of the global values that may be referenced are available in our
1332361e513dSReid Spencer   // ValueMap.
13333aaaa0b2SReid Spencer   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1334361e513dSReid Spencer     return true;
1335361e513dSReid Spencer 
13362e13597fSAnton Korobeynikov   // If there were any alias, link them now. We really need to do this now,
13372e13597fSAnton Korobeynikov   // because all of the aliases that may be referenced need to be available in
13382e13597fSAnton Korobeynikov   // ValueMap
13392e13597fSAnton Korobeynikov   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
13402e13597fSAnton Korobeynikov 
1341361e513dSReid Spencer   // Update the initializers in the Dest module now that all globals that may
1342361e513dSReid Spencer   // be referenced are in Dest.
1343361e513dSReid Spencer   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1344361e513dSReid Spencer 
1345361e513dSReid Spencer   // Link in the function bodies that are defined in the source module into the
1346361e513dSReid Spencer   // DestModule.  This consists basically of copying the function over and
1347361e513dSReid Spencer   // fixing up references to values.
1348361e513dSReid Spencer   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1349361e513dSReid Spencer 
1350361e513dSReid Spencer   // If there were any appending global variables, link them together now.
1351361e513dSReid Spencer   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1352361e513dSReid Spencer 
1353e43711d3SAnton Korobeynikov   // Resolve all uses of aliases with aliasees
1354e43711d3SAnton Korobeynikov   if (ResolveAliases(Dest)) return true;
1355e43711d3SAnton Korobeynikov 
1356361e513dSReid Spencer   // If the source library's module id is in the dependent library list of the
1357361e513dSReid Spencer   // destination library, remove it since that module is now linked in.
1358361e513dSReid Spencer   sys::Path modId;
1359c9c0473fSReid Spencer   modId.set(Src->getModuleIdentifier());
1360361e513dSReid Spencer   if (!modId.isEmpty())
1361361e513dSReid Spencer     Dest->removeLibrary(modId.getBasename());
1362361e513dSReid Spencer 
1363361e513dSReid Spencer   return false;
1364361e513dSReid Spencer }
1365361e513dSReid Spencer 
1366361e513dSReid Spencer // vim: sw=2
1367