blob: 27c71b16186f1b4cf34804e3a0d7fed64a59c0dc [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM module linker.
11//
12// Specifically, this:
13// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15// * Merges functions between two modules
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Linker.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Module.h"
23#include "llvm/TypeSymbolTable.h"
24#include "llvm/ValueSymbolTable.h"
25#include "llvm/Instructions.h"
26#include "llvm/Assembly/Writer.h"
27#include "llvm/Support/Streams.h"
28#include "llvm/System/Path.h"
Chris Lattner0b228bf2008-06-16 21:00:18 +000029#include "llvm/ADT/DenseMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include <sstream>
31using namespace llvm;
32
33// Error - Simple wrapper function to conditionally assign to E and return true.
34// This just makes error return conditions a little bit simpler...
35static inline bool Error(std::string *E, const std::string &Message) {
36 if (E) *E = Message;
37 return true;
38}
39
40// ToStr - Simple wrapper function to convert a type to a string.
41static std::string ToStr(const Type *Ty, const Module *M) {
42 std::ostringstream OS;
43 WriteTypeSymbolic(OS, Ty, M);
44 return OS.str();
45}
46
47//
48// Function: ResolveTypes()
49//
50// Description:
51// Attempt to link the two specified types together.
52//
53// Inputs:
54// DestTy - The type to which we wish to resolve.
55// SrcTy - The original type which we want to resolve.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056//
57// Outputs:
58// DestST - The symbol table in which the new type should be placed.
59//
60// Return value:
61// true - There is an error and the types cannot yet be linked.
62// false - No errors.
63//
Chris Lattner06638ab2008-06-16 18:19:05 +000064static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattner06638ab2008-06-16 18:19:05 +000066 assert(DestTy && SrcTy && "Can't handle null types");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067
Chris Lattner06638ab2008-06-16 18:19:05 +000068 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
69 // Type _is_ in module, just opaque...
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
71 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
72 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
73 } else {
74 return true; // Cannot link types... not-equal and neither is opaque.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 }
76 return false;
77}
78
Chris Lattner0b228bf2008-06-16 21:00:18 +000079/// LinkerTypeMap - This implements a map of types that is stable
80/// even if types are resolved/refined to other types. This is not a general
81/// purpose map, it is specific to the linker's use.
82namespace {
83class LinkerTypeMap : public AbstractTypeUser {
84 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
85 TheMapTy TheMap;
86public:
87
88 LinkerTypeMap() {
89 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
90 E = TheMap.end(); I != E; ++I)
91 I->first->removeAbstractTypeUser(this);
92 }
93
94 /// lookup - Return the value for the specified type or null if it doesn't
95 /// exist.
96 const Type *lookup(const Type *Ty) const {
97 TheMapTy::const_iterator I = TheMap.find(Ty);
98 if (I != TheMap.end()) return I->second;
99 return 0;
100 }
101
102 /// erase - Remove the specified type, returning true if it was in the set.
103 bool erase(const Type *Ty) {
104 if (!TheMap.erase(Ty))
105 return false;
106 if (Ty->isAbstract())
107 Ty->removeAbstractTypeUser(this);
108 return true;
109 }
110
111 /// insert - This returns true if the pointer was new to the set, false if it
112 /// was already in the set.
113 bool insert(const Type *Src, const Type *Dst) {
114 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))))
115 return false; // Already in map.
116 if (Src->isAbstract())
117 Src->addAbstractTypeUser(this);
118 return true;
119 }
120
121protected:
122 /// refineAbstractType - The callback method invoked when an abstract type is
123 /// resolved to another type. An object must override this method to update
124 /// its internal state to reference NewType instead of OldType.
125 ///
126 virtual void refineAbstractType(const DerivedType *OldTy,
127 const Type *NewTy) {
128 TheMapTy::iterator I = TheMap.find(OldTy);
129 const Type *DstTy = I->second;
130
131 TheMap.erase(I);
132 if (OldTy->isAbstract())
133 OldTy->removeAbstractTypeUser(this);
134
135 // Don't reinsert into the map if the key is concrete now.
136 if (NewTy->isAbstract())
137 insert(NewTy, DstTy);
138 }
139
140 /// The other case which AbstractTypeUsers must be aware of is when a type
141 /// makes the transition from being abstract (where it has clients on it's
142 /// AbstractTypeUsers list) to concrete (where it does not). This method
143 /// notifies ATU's when this occurs for a type.
144 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
145 TheMap.erase(AbsTy);
146 AbsTy->removeAbstractTypeUser(this);
147 }
148
149 // for debugging...
150 virtual void dump() const {
151 cerr << "AbstractTypeSet!\n";
152 }
153};
154}
155
156
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157// RecursiveResolveTypes - This is just like ResolveTypes, except that it
158// recurses down into derived types, merging the used types if the parent types
159// are compatible.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000160static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner0b228bf2008-06-16 21:00:18 +0000161 LinkerTypeMap &Pointers) {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000162 if (DstTy == SrcTy) return false; // If already equal, noop
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163
164 // If we found our opaque type, resolve it now!
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000165 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
166 return ResolveTypes(DstTy, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
168 // Two types cannot be resolved together if they are of different primitive
169 // type. For example, we cannot resolve an int to a float.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000170 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171
Chris Lattnere174d322008-06-16 20:03:01 +0000172 // If neither type is abstract, then they really are just different types.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000173 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattnere174d322008-06-16 20:03:01 +0000174 return true;
175
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000177 switch (DstTy->getTypeID()) {
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000178 default:
179 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 case Type::FunctionTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000181 const FunctionType *DstFT = cast<FunctionType>(DstTy);
182 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000183 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
184 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000186
187 // Use TypeHolder's so recursive resolution won't break us.
188 PATypeHolder ST(SrcFT), DT(DstFT);
189 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
190 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
191 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000193 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 return false;
195 }
196 case Type::StructTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000197 const StructType *DstST = cast<StructType>(DstTy);
198 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000199 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000200 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000201
202 PATypeHolder ST(SrcST), DT(DstST);
203 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
204 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
205 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000207 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 return false;
209 }
210 case Type::ArrayTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000211 const ArrayType *DAT = cast<ArrayType>(DstTy);
212 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 if (DAT->getNumElements() != SAT->getNumElements()) return true;
214 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattner06638ab2008-06-16 18:19:05 +0000215 Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 }
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000217 case Type::VectorTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000218 const VectorType *DVT = cast<VectorType>(DstTy);
219 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000220 if (DVT->getNumElements() != SVT->getNumElements()) return true;
221 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
222 Pointers);
223 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 case Type::PointerTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000225 const PointerType *DstPT = cast<PointerType>(DstTy);
226 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000227
228 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
229 return true;
230
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 // If this is a pointer type, check to see if we have already seen it. If
232 // so, we are in a recursive branch. Cut off the search now. We cannot use
233 // an associative container for this search, because the type pointers (keys
Chris Lattner0b228bf2008-06-16 21:00:18 +0000234 // in the container) change whenever types get resolved.
235 if (SrcPT->isAbstract())
236 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
237 return ExistingDestTy != DstPT;
238
239 if (DstPT->isAbstract())
240 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
241 return ExistingSrcTy != SrcPT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 // Otherwise, add the current pointers to the vector to stop recursion on
243 // this pair.
Chris Lattner0b228bf2008-06-16 21:00:18 +0000244 if (DstPT->isAbstract())
245 Pointers.insert(DstPT, SrcPT);
246 if (SrcPT->isAbstract())
247 Pointers.insert(SrcPT, DstPT);
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000248
Chris Lattner41fed262008-06-16 19:55:40 +0000249 return RecursiveResolveTypesI(DstPT->getElementType(),
250 SrcPT->getElementType(), Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 }
253}
254
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000255static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner0b228bf2008-06-16 21:00:18 +0000256 LinkerTypeMap PointerTypes;
Chris Lattner06638ab2008-06-16 18:19:05 +0000257 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258}
259
260
261// LinkTypes - Go through the symbol table of the Src module and see if any
262// types are named in the src module that are not named in the Dst module.
263// Make sure there are no type name conflicts.
264static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
265 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
266 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
267
268 // Look for a type plane for Type's...
269 TypeSymbolTable::const_iterator TI = SrcST->begin();
270 TypeSymbolTable::const_iterator TE = SrcST->end();
271 if (TI == TE) return false; // No named types, do nothing.
272
273 // Some types cannot be resolved immediately because they depend on other
274 // types being resolved to each other first. This contains a list of types we
275 // are waiting to recheck.
276 std::vector<std::string> DelayedTypesToResolve;
277
278 for ( ; TI != TE; ++TI ) {
279 const std::string &Name = TI->first;
280 const Type *RHS = TI->second;
281
Chris Lattner06638ab2008-06-16 18:19:05 +0000282 // Check to see if this type name is already in the dest module.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 Type *Entry = DestST->lookup(Name);
284
Chris Lattner06638ab2008-06-16 18:19:05 +0000285 // If the name is just in the source module, bring it over to the dest.
286 if (Entry == 0) {
287 if (!Name.empty())
288 DestST->insert(Name, const_cast<Type*>(RHS));
289 } else if (ResolveTypes(Entry, RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 // They look different, save the types 'till later to resolve.
291 DelayedTypesToResolve.push_back(Name);
292 }
293 }
294
295 // Iteratively resolve types while we can...
296 while (!DelayedTypesToResolve.empty()) {
297 // Loop over all of the types, attempting to resolve them if possible...
298 unsigned OldSize = DelayedTypesToResolve.size();
299
300 // Try direct resolution by name...
301 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
302 const std::string &Name = DelayedTypesToResolve[i];
303 Type *T1 = SrcST->lookup(Name);
304 Type *T2 = DestST->lookup(Name);
Chris Lattner06638ab2008-06-16 18:19:05 +0000305 if (!ResolveTypes(T2, T1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 // We are making progress!
307 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
308 --i;
309 }
310 }
311
312 // Did we not eliminate any types?
313 if (DelayedTypesToResolve.size() == OldSize) {
314 // Attempt to resolve subelements of types. This allows us to merge these
315 // two types: { int* } and { opaque* }
316 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
317 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000318 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 // We are making progress!
320 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
321
322 // Go back to the main loop, perhaps we can resolve directly by name
323 // now...
324 break;
325 }
326 }
327
328 // If we STILL cannot resolve the types, then there is something wrong.
329 if (DelayedTypesToResolve.size() == OldSize) {
330 // Remove the symbol name from the destination.
331 DelayedTypesToResolve.pop_back();
332 }
333 }
334 }
335
336
337 return false;
338}
339
340static void PrintMap(const std::map<const Value*, Value*> &M) {
341 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
342 I != E; ++I) {
343 cerr << " Fr: " << (void*)I->first << " ";
344 I->first->dump();
345 cerr << " To: " << (void*)I->second << " ";
346 I->second->dump();
347 cerr << "\n";
348 }
349}
350
351
352// RemapOperand - Use ValueMap to convert constants from one module to another.
353static Value *RemapOperand(const Value *In,
354 std::map<const Value*, Value*> &ValueMap) {
355 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
356 if (I != ValueMap.end())
357 return I->second;
358
359 // Check to see if it's a constant that we are interested in transforming.
360 Value *Result = 0;
361 if (const Constant *CPV = dyn_cast<Constant>(In)) {
362 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
363 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
364 return const_cast<Constant*>(CPV); // Simple constants stay identical.
365
366 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
367 std::vector<Constant*> Operands(CPA->getNumOperands());
368 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
369 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
370 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
371 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
372 std::vector<Constant*> Operands(CPS->getNumOperands());
373 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
374 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
375 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
376 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
377 Result = const_cast<Constant*>(CPV);
378 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
379 std::vector<Constant*> Operands(CP->getNumOperands());
380 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
381 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
382 Result = ConstantVector::get(Operands);
383 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
384 std::vector<Constant*> Ops;
385 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
386 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
387 Result = CE->getWithOperands(Ops);
388 } else if (isa<GlobalValue>(CPV)) {
389 assert(0 && "Unmapped global?");
390 } else {
391 assert(0 && "Unknown type of derived type constant value!");
392 }
393 } else if (isa<InlineAsm>(In)) {
394 Result = const_cast<Value*>(In);
395 }
396
397 // Cache the mapping in our local map structure
398 if (Result) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000399 ValueMap[In] = Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 return Result;
401 }
402
403
404 cerr << "LinkModules ValueMap: \n";
405 PrintMap(ValueMap);
406
407 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
408 assert(0 && "Couldn't remap value!");
409 return 0;
410}
411
412/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
413/// in the symbol table. This is good for all clients except for us. Go
414/// through the trouble to force this back.
415static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
416 assert(GV->getName() != Name && "Can't force rename to self");
417 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
418
419 // If there is a conflict, rename the conflict.
420 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
421 assert(ConflictGV->hasInternalLinkage() &&
422 "Not conflicting with a static global, should link instead!");
423 GV->takeName(ConflictGV);
424 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
425 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
426 } else {
427 GV->setName(Name); // Force the name back
428 }
429}
430
431/// CopyGVAttributes - copy additional attributes (those not needed to construct
432/// a GlobalValue) from the SrcGV to the DestGV.
433static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands0cc90582008-05-26 19:58:59 +0000434 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
435 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
436 DestGV->copyAttributesFrom(SrcGV);
437 DestGV->setAlignment(Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438}
439
440/// GetLinkageResult - This analyzes the two global values and determines what
441/// the result will look like in the destination module. In particular, it
442/// computes the resultant linkage type, computes whether the global in the
443/// source should be copied over to the destination (replacing the existing
444/// one), and computes whether this linkage is an error or not. It also performs
445/// visibility checks: we cannot link together two symbols with different
446/// visibilities.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000447static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
449 std::string *Err) {
450 assert((!Dest || !Src->hasInternalLinkage()) &&
451 "If Src has internal linkage, Dest shouldn't be set!");
452 if (!Dest) {
453 // Linking something to nothing.
454 LinkFromSrc = true;
455 LT = Src->getLinkage();
456 } else if (Src->isDeclaration()) {
Anton Korobeynikov15520982008-03-10 22:33:22 +0000457 // If Src is external or if both Src & Dest are external.. Just link the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 // external globals, we aren't adding anything.
459 if (Src->hasDLLImportLinkage()) {
460 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
461 if (Dest->isDeclaration()) {
462 LinkFromSrc = true;
463 LT = Src->getLinkage();
464 }
465 } else if (Dest->hasExternalWeakLinkage()) {
466 //If the Dest is weak, use the source linkage
467 LinkFromSrc = true;
468 LT = Src->getLinkage();
469 } else {
470 LinkFromSrc = false;
471 LT = Dest->getLinkage();
472 }
473 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
474 // If Dest is external but Src is not:
475 LinkFromSrc = true;
476 LT = Src->getLinkage();
477 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
478 if (Src->getLinkage() != Dest->getLinkage())
479 return Error(Err, "Linking globals named '" + Src->getName() +
480 "': can only link appending global with another appending global!");
481 LinkFromSrc = true; // Special cased.
482 LT = Src->getLinkage();
Dale Johannesen49c44122008-05-14 20:12:51 +0000483 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
484 Src->hasCommonLinkage()) {
485 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
486 // or DLL* linkage.
487 if ((Dest->hasLinkOnceLinkage() &&
488 (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 Dest->hasExternalWeakLinkage()) {
490 LinkFromSrc = true;
491 LT = Src->getLinkage();
492 } else {
493 LinkFromSrc = false;
494 LT = Dest->getLinkage();
495 }
Dale Johannesen49c44122008-05-14 20:12:51 +0000496 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
497 Dest->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 // At this point we know that Src has External* or DLL* linkage.
499 if (Src->hasExternalWeakLinkage()) {
500 LinkFromSrc = false;
501 LT = Dest->getLinkage();
502 } else {
503 LinkFromSrc = true;
504 LT = GlobalValue::ExternalLinkage;
505 }
506 } else {
507 assert((Dest->hasExternalLinkage() ||
508 Dest->hasDLLImportLinkage() ||
509 Dest->hasDLLExportLinkage() ||
510 Dest->hasExternalWeakLinkage()) &&
511 (Src->hasExternalLinkage() ||
512 Src->hasDLLImportLinkage() ||
513 Src->hasDLLExportLinkage() ||
514 Src->hasExternalWeakLinkage()) &&
515 "Unexpected linkage type!");
516 return Error(Err, "Linking globals named '" + Src->getName() +
517 "': symbol multiply defined!");
518 }
519
520 // Check visibility
521 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000522 if (!Src->isDeclaration() && !Dest->isDeclaration())
523 return Error(Err, "Linking globals named '" + Src->getName() +
524 "': symbols have different visibilities!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 return false;
526}
527
528// LinkGlobals - Loop through the global variables in the src module and merge
529// them into the dest module.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000530static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 std::map<const Value*, Value*> &ValueMap,
532 std::multimap<std::string, GlobalVariable *> &AppendingVars,
533 std::string *Err) {
534 // Loop over all of the globals in the src module, mapping them over as we go
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000535 for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 I != E; ++I) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000537 const GlobalVariable *SGV = I;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000538 GlobalValue *DGV = 0;
539
540 // Check to see if may have to link the global with the global
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 if (SGV->hasName() && !SGV->hasInternalLinkage()) {
542 DGV = Dest->getGlobalVariable(SGV->getName());
543 if (DGV && DGV->getType() != SGV->getType())
544 // If types don't agree due to opaque types, try to resolve them.
Chris Lattner06638ab2008-06-16 18:19:05 +0000545 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 }
547
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000548 // Check to see if may have to link the global with the alias
Anton Korobeynikov702d1cd2008-03-10 22:35:31 +0000549 if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000550 DGV = Dest->getNamedAlias(SGV->getName());
551 if (DGV && DGV->getType() != SGV->getType())
552 // If types don't agree due to opaque types, try to resolve them.
Chris Lattner06638ab2008-06-16 18:19:05 +0000553 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000554 }
555
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 if (DGV && DGV->hasInternalLinkage())
557 DGV = 0;
558
Dan Gohman930191f2007-10-08 15:13:30 +0000559 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
560 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 "Global must either be external or have an initializer!");
562
563 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
564 bool LinkFromSrc = false;
565 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
566 return true;
567
568 if (!DGV) {
569 // No linking to be performed, simply create an identical version of the
570 // symbol over in the dest module... the initializer will be filled in
571 // later by LinkGlobalInits...
572 GlobalVariable *NewDGV =
573 new GlobalVariable(SGV->getType()->getElementType(),
574 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikov2bde2d82008-03-07 18:32:18 +0000575 SGV->getName(), Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576 // Propagate alignment, visibility and section info.
577 CopyGVAttributes(NewDGV, SGV);
578
579 // If the LLVM runtime renamed the global, but it is an externally visible
580 // symbol, DGV must be an existing global with internal linkage. Rename
581 // it.
582 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
583 ForceRenaming(NewDGV, SGV->getName());
584
585 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000586 ValueMap[SGV] = NewDGV;
587
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 if (SGV->hasAppendingLinkage())
589 // Keep track that this is an appending variable...
590 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
591 } else if (DGV->hasAppendingLinkage()) {
592 // No linking is performed yet. Just insert a new copy of the global, and
593 // keep track of the fact that it is an appending variable in the
594 // AppendingVars map. The name is cleared out so that no linkage is
595 // performed.
596 GlobalVariable *NewDGV =
597 new GlobalVariable(SGV->getType()->getElementType(),
598 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikov2bde2d82008-03-07 18:32:18 +0000599 "", Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000601 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000603 // Propagate alignment, section and visibility info.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 CopyGVAttributes(NewDGV, SGV);
605
606 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000607 ValueMap[SGV] = NewDGV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608
609 // Keep track that this is an appending variable...
610 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000611 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
612 // SGV is global, but DGV is alias. The only valid mapping is when SGV is
613 // external declaration, which is effectively a no-op. Also make sure
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000614 // linkage calculation was correct.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000615 if (SGV->isDeclaration() && !LinkFromSrc) {
616 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000617 ValueMap[SGV] = DGA;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000618 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000619 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
620 "': symbol multiple defined");
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000621 } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000622 // Otherwise, perform the global-global mapping as instructed by
623 // GetLinkageResult.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 if (LinkFromSrc) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000625 // Propagate alignment, section, and visibility info.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000626 CopyGVAttributes(DGVar, SGV);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000627
628 // If the types don't match, and if we are to link from the source, nuke
629 // DGV and create a new one of the appropriate type.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000630 if (SGV->getType() != DGVar->getType()) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000631 GlobalVariable *NewDGV =
632 new GlobalVariable(SGV->getType()->getElementType(),
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000633 DGVar->isConstant(), DGVar->getLinkage(),
634 /*init*/0, DGVar->getName(), Dest);
635 CopyGVAttributes(NewDGV, DGVar);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000636 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000637 DGVar->getType()));
638 // DGVar will conflict with NewDGV because they both had the same
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000639 // name. We must erase this now so ForceRenaming doesn't assert
640 // because DGV might not have internal linkage.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000641 DGVar->eraseFromParent();
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000642
643 // If the symbol table renamed the global, but it is an externally
644 // visible symbol, DGV must be an existing global with internal
645 // linkage. Rename it.
646 if (NewDGV->getName() != SGV->getName() &&
647 !NewDGV->hasInternalLinkage())
648 ForceRenaming(NewDGV, SGV->getName());
649
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000650 DGVar = NewDGV;
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000651 }
652
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 // Inherit const as appropriate
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000654 DGVar->setConstant(SGV->isConstant());
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000655
656 // Set initializer to zero, so we can link the stuff later
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000657 DGVar->setInitializer(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 } else {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000659 // Special case for const propagation
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000660 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
661 DGVar->setConstant(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 }
663
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000664 // Set calculated linkage
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000665 DGVar->setLinkage(NewLinkage);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000666
667 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000668 ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 }
670 }
671 return false;
672}
673
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000674static GlobalValue::LinkageTypes
675CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
676 if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
677 return GlobalValue::ExternalLinkage;
678 else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
679 return GlobalValue::WeakLinkage;
680 else {
681 assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
682 "Unexpected linkage type");
683 return GlobalValue::InternalLinkage;
684 }
685}
686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000688// dest module. We're assuming, that all functions/global variables were already
689// linked in.
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000690static bool LinkAlias(Module *Dest, const Module *Src,
691 std::map<const Value*, Value*> &ValueMap,
692 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693 // Loop over all alias in the src module
694 for (Module::const_alias_iterator I = Src->alias_begin(),
695 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000696 const GlobalAlias *SGA = I;
697 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
698 GlobalAlias *NewGA = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000700 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000701 // of SAliasee in Dest.
Ted Kremenekd40cdd22008-03-09 18:32:50 +0000702 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
703 assert(VMI != ValueMap.end() && "Aliasee not linked");
704 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000705 GlobalValue* DGV = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000707 // Try to find something 'similar' to SGA in destination module.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000708 if (!DGV && !SGA->hasInternalLinkage()) {
709 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000710
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000711 // If types don't agree due to opaque types, try to resolve them.
712 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000713 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000714 return Error(Err, "Alias Collision on '" + SGA->getName()+
715 "': aliases have different types");
716 }
717
718 if (!DGV && !SGA->hasInternalLinkage()) {
719 DGV = Dest->getGlobalVariable(SGA->getName());
720
721 // If types don't agree due to opaque types, try to resolve them.
722 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000723 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000724 return Error(Err, "Alias Collision on '" + SGA->getName()+
725 "': aliases have different types");
726 }
727
728 if (!DGV && !SGA->hasInternalLinkage()) {
729 DGV = Dest->getFunction(SGA->getName());
730
731 // If types don't agree due to opaque types, try to resolve them.
732 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000733 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000734 return Error(Err, "Alias Collision on '" + SGA->getName()+
735 "': aliases have different types");
736 }
737
738 // No linking to be performed on internal stuff.
739 if (DGV && DGV->hasInternalLinkage())
740 DGV = NULL;
741
742 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
743 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000744 // globals are already linked we just need query ValueMap to find the
745 // mapping.
746 if (DAliasee == DGA->getAliasedGlobal()) {
747 // This is just two copies of the same alias. Propagate linkage, if
748 // necessary.
749 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
750
751 NewGA = DGA;
752 // Proceed to 'common' steps
753 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000754 return Error(Err, "Alias Collision on '" + SGA->getName()+
755 "': aliases have different aliasees");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000756 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000757 // The only allowed way is to link alias with external declaration.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000758 if (DGVar->isDeclaration()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000759 // But only if aliasee is global too...
760 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000761 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
762 "': aliasee is not global variable");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000763
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000764 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
765 SGA->getName(), DAliasee, Dest);
766 CopyGVAttributes(NewGA, SGA);
767
768 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000769 if (SGA->getType() != DGVar->getType())
770 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
771 DGVar->getType()));
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000772 else
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000773 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000774
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000775 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000776 // name. We must erase this now so ForceRenaming doesn't assert
777 // because DGV might not have internal linkage.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000778 DGVar->eraseFromParent();
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000779
780 // Proceed to 'common' steps
781 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000782 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
783 "': symbol multiple defined");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000784 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000785 // The only allowed way is to link alias with external declaration.
786 if (DF->isDeclaration()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000787 // But only if aliasee is function too...
788 if (!isa<Function>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000789 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
790 "': aliasee is not function");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000791
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000792 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
793 SGA->getName(), DAliasee, Dest);
794 CopyGVAttributes(NewGA, SGA);
795
796 // Any uses of DF need to change to NewGA, with cast, if needed.
797 if (SGA->getType() != DF->getType())
798 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
799 DF->getType()));
800 else
801 DF->replaceAllUsesWith(NewGA);
802
803 // DF will conflict with NewGA because they both had the same
804 // name. We must erase this now so ForceRenaming doesn't assert
805 // because DF might not have internal linkage.
806 DF->eraseFromParent();
807
808 // Proceed to 'common' steps
809 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000810 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
811 "': symbol multiple defined");
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000812 } else {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000813 // No linking to be performed, simply create an identical version of the
814 // alias over in the dest module...
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000815
816 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
817 SGA->getName(), DAliasee, Dest);
818 CopyGVAttributes(NewGA, SGA);
819
820 // Proceed to 'common' steps
821 }
822
823 assert(NewGA && "No alias was created in destination module!");
824
Anton Korobeynikov552ccce2008-03-10 22:36:35 +0000825 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000826 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000827 if (NewGA->getName() != SGA->getName() &&
828 !NewGA->hasInternalLinkage())
829 ForceRenaming(NewGA, SGA->getName());
830
831 // Remember this mapping so uses in the source module get remapped
832 // later by RemapOperand.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000833 ValueMap[SGA] = NewGA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 }
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000835
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 return false;
837}
838
839
840// LinkGlobalInits - Update the initializers in the Dest module now that all
841// globals that may be referenced are in Dest.
842static bool LinkGlobalInits(Module *Dest, const Module *Src,
843 std::map<const Value*, Value*> &ValueMap,
844 std::string *Err) {
845
846 // Loop over all of the globals in the src module, mapping them over as we go
847 for (Module::const_global_iterator I = Src->global_begin(),
848 E = Src->global_end(); I != E; ++I) {
849 const GlobalVariable *SGV = I;
850
851 if (SGV->hasInitializer()) { // Only process initialized GV's
852 // Figure out what the initializer looks like in the dest module...
853 Constant *SInit =
854 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
855
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +0000856 GlobalVariable *DGV =
857 cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 if (DGV->hasInitializer()) {
859 if (SGV->hasExternalLinkage()) {
860 if (DGV->getInitializer() != SInit)
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000861 return Error(Err, "Global Variable Collision on '" + SGV->getName() +
862 "': global variables have different initializers");
Dale Johannesen49c44122008-05-14 20:12:51 +0000863 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
864 DGV->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 // Nothing is required, mapped values will take the new global
866 // automatically.
Dale Johannesen49c44122008-05-14 20:12:51 +0000867 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
868 SGV->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000869 // Nothing is required, mapped values will take the new global
870 // automatically.
871 } else if (DGV->hasAppendingLinkage()) {
872 assert(0 && "Appending linkage unimplemented!");
873 } else {
874 assert(0 && "Unknown linkage!");
875 }
876 } else {
877 // Copy the initializer over now...
878 DGV->setInitializer(SInit);
879 }
880 }
881 }
882 return false;
883}
884
885// LinkFunctionProtos - Link the functions together between the two modules,
886// without doing function bodies... this just adds external function prototypes
887// to the Dest function...
888//
889static bool LinkFunctionProtos(Module *Dest, const Module *Src,
890 std::map<const Value*, Value*> &ValueMap,
891 std::string *Err) {
892 // Loop over all of the functions in the src module, mapping them over
893 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
894 const Function *SF = I; // SrcFunction
Chris Lattner1426bfa2008-06-09 07:36:11 +0000895
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 Function *DF = 0;
Chris Lattner1426bfa2008-06-09 07:36:11 +0000897
898 // If this function is internal or has no name, it doesn't participate in
899 // linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 if (SF->hasName() && !SF->hasInternalLinkage()) {
901 // Check to see if may have to link the function.
902 DF = Dest->getFunction(SF->getName());
Chris Lattner1426bfa2008-06-09 07:36:11 +0000903 if (DF && DF->hasInternalLinkage())
904 DF = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 }
Chris Lattnerf7e84192008-06-09 07:25:28 +0000906
Chris Lattner1426bfa2008-06-09 07:36:11 +0000907 // If there is no linkage to be performed, just bring over SF without
908 // modifying it.
909 if (DF == 0) {
910 // Function does not already exist, simply insert an function signature
911 // identical to SF into the dest module.
912 Function *NewDF = Function::Create(SF->getFunctionType(),
913 SF->getLinkage(),
914 SF->getName(), Dest);
915 CopyGVAttributes(NewDF, SF);
916
917 // If the LLVM runtime renamed the function, but it is an externally
918 // visible symbol, DF must be an existing function with internal linkage.
919 // Rename it.
920 if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
921 ForceRenaming(NewDF, SF->getName());
922
923 // ... and remember this mapping...
924 ValueMap[SF] = NewDF;
925 continue;
926 }
927
928
929 // If types don't agree because of opaque, try to resolve them.
930 if (SF->getType() != DF->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000931 RecursiveResolveTypes(SF->getType(), DF->getType());
Chris Lattner1426bfa2008-06-09 07:36:11 +0000932
933 // Check visibility, merging if a definition overrides a prototype.
934 if (SF->getVisibility() != DF->getVisibility()) {
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000935 // If one is a prototype, ignore its visibility. Prototypes are always
936 // overridden by the definition.
937 if (!SF->isDeclaration() && !DF->isDeclaration())
938 return Error(Err, "Linking functions named '" + SF->getName() +
939 "': symbols have different visibilities!");
Chris Lattnerf7e84192008-06-09 07:25:28 +0000940
941 // Otherwise, replace the visibility of DF if DF is a prototype.
942 if (DF->isDeclaration())
943 DF->setVisibility(SF->getVisibility());
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000944 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945
Chris Lattner1426bfa2008-06-09 07:36:11 +0000946 if (DF->getType() != SF->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 if (DF->isDeclaration() && !SF->isDeclaration()) {
948 // We have a definition of the same name but different type in the
949 // source module. Copy the prototype to the destination and replace
950 // uses of the destination's prototype with the new prototype.
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000951 Function *NewDF = Function::Create(SF->getFunctionType(),
952 SF->getLinkage(),
Gabor Greifd6da1d02008-04-06 20:25:17 +0000953 SF->getName(), Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 CopyGVAttributes(NewDF, SF);
955
956 // Any uses of DF need to change to NewDF, with cast
957 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
958
959 // DF will conflict with NewDF because they both had the same. We must
960 // erase this now so ForceRenaming doesn't assert because DF might
961 // not have internal linkage.
962 DF->eraseFromParent();
963
964 // If the symbol table renamed the function, but it is an externally
965 // visible symbol, DF must be an existing function with internal
966 // linkage. Rename it.
967 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
968 ForceRenaming(NewDF, SF->getName());
969
970 // Remember this mapping so uses in the source module get remapped
971 // later by RemapOperand.
972 ValueMap[SF] = NewDF;
973 } else if (SF->isDeclaration()) {
974 // We have two functions of the same name but different type and the
975 // source is a declaration while the destination is not. Any use of
976 // the source must be mapped to the destination, with a cast.
977 ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType());
978 } else {
979 // We have two functions of the same name but different types and they
980 // are both definitions. This is an error.
981 return Error(Err, "Function '" + DF->getName() + "' defined as both '" +
982 ToStr(SF->getFunctionType(), Src) + "' and '" +
983 ToStr(DF->getFunctionType(), Dest) + "'");
984 }
Chris Lattner1426bfa2008-06-09 07:36:11 +0000985 continue;
986 }
987
988 if (SF->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 // If SF is a declaration or if both SF & DF are declarations, just link
990 // the declarations, we aren't adding anything.
991 if (SF->hasDLLImportLinkage()) {
992 if (DF->isDeclaration()) {
Chris Lattnerc082fd42008-06-09 07:47:34 +0000993 ValueMap[SF] = DF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000995 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 } else {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000997 ValueMap[SF] = DF;
Chris Lattnerc082fd42008-06-09 07:47:34 +0000998 }
999 continue;
1000 }
1001
1002 // If DF is external but SF is not, link the external functions, update
1003 // linkage qualifiers.
1004 if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 ValueMap.insert(std::make_pair(SF, DF));
1006 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +00001007 continue;
1008 }
1009
1010 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
1011 if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
1012 SF->hasCommonLinkage()) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +00001013 ValueMap[SF] = DF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014
1015 // Linkonce+Weak = Weak
1016 // *+External Weak = *
Dale Johannesen49c44122008-05-14 20:12:51 +00001017 if ((DF->hasLinkOnceLinkage() &&
1018 (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 DF->hasExternalWeakLinkage())
1020 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +00001021 continue;
1022 }
1023
1024 if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
1025 DF->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 // At this point we know that SF has LinkOnce or External* linkage.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +00001027 ValueMap[SF] = DF;
Chris Lattnerc082fd42008-06-09 07:47:34 +00001028
1029 // If the source function has stronger linkage than the destination,
1030 // its body and linkage should override ours.
1031 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
1032 // Don't inherit linkonce & external weak linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +00001034 DF->deleteBody();
1035 }
1036 continue;
1037 }
1038
1039 if (SF->getLinkage() != DF->getLinkage())
1040 return Error(Err, "Functions named '" + SF->getName() +
1041 "' have different linkage specifiers!");
1042
1043 // The function is defined identically in both modules!
1044 if (SF->hasExternalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 return Error(Err, "Function '" +
1046 ToStr(SF->getFunctionType(), Src) + "':\"" +
1047 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc082fd42008-06-09 07:47:34 +00001048 assert(0 && "Unknown linkage configuration found!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049 }
1050 return false;
1051}
1052
1053// LinkFunctionBody - Copy the source function over into the dest function and
1054// fix up references to values. At this point we know that Dest is an external
1055// function, and that Src is not.
1056static bool LinkFunctionBody(Function *Dest, Function *Src,
1057 std::map<const Value*, Value*> &ValueMap,
1058 std::string *Err) {
1059 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1060
1061 // Go through and convert function arguments over, remembering the mapping.
1062 Function::arg_iterator DI = Dest->arg_begin();
1063 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1064 I != E; ++I, ++DI) {
Owen Andersonab567f82008-04-14 17:38:21 +00001065 DI->setName(I->getName()); // Copy the name information over...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066
1067 // Add a mapping to our local map
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +00001068 ValueMap[I] = DI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 }
1070
1071 // Splice the body of the source function into the dest function.
1072 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1073
1074 // At this point, all of the instructions and values of the function are now
1075 // copied over. The only problem is that they are still referencing values in
1076 // the Source function as operands. Loop through all of the operands of the
1077 // functions and patch them up to point to the local versions...
1078 //
1079 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1080 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1081 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1082 OI != OE; ++OI)
1083 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1084 *OI = RemapOperand(*OI, ValueMap);
1085
1086 // There is no need to map the arguments anymore.
1087 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1088 I != E; ++I)
1089 ValueMap.erase(I);
1090
1091 return false;
1092}
1093
1094
1095// LinkFunctionBodies - Link in the function bodies that are defined in the
1096// source module into the DestModule. This consists basically of copying the
1097// function over and fixing up references to values.
1098static bool LinkFunctionBodies(Module *Dest, Module *Src,
1099 std::map<const Value*, Value*> &ValueMap,
1100 std::string *Err) {
1101
1102 // Loop over all of the functions in the src module, mapping them over as we
1103 // go
1104 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1105 if (!SF->isDeclaration()) { // No body if function is external
1106 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
1107
1108 // DF not external SF external?
1109 if (DF->isDeclaration())
1110 // Only provide the function body if there isn't one already.
1111 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1112 return true;
1113 }
1114 }
1115 return false;
1116}
1117
1118// LinkAppendingVars - If there were any appending global variables, link them
1119// together now. Return true on error.
1120static bool LinkAppendingVars(Module *M,
1121 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1122 std::string *ErrorMsg) {
1123 if (AppendingVars.empty()) return false; // Nothing to do.
1124
1125 // Loop over the multimap of appending vars, processing any variables with the
1126 // same name, forming a new appending global variable with both of the
1127 // initializers merged together, then rewrite references to the old variables
1128 // and delete them.
1129 std::vector<Constant*> Inits;
1130 while (AppendingVars.size() > 1) {
1131 // Get the first two elements in the map...
1132 std::multimap<std::string,
1133 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1134
1135 // If the first two elements are for different names, there is no pair...
1136 // Otherwise there is a pair, so link them together...
1137 if (First->first == Second->first) {
1138 GlobalVariable *G1 = First->second, *G2 = Second->second;
1139 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1140 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1141
1142 // Check to see that they two arrays agree on type...
1143 if (T1->getElementType() != T2->getElementType())
1144 return Error(ErrorMsg,
1145 "Appending variables with different element types need to be linked!");
1146 if (G1->isConstant() != G2->isConstant())
1147 return Error(ErrorMsg,
1148 "Appending variables linked with different const'ness!");
1149
1150 if (G1->getAlignment() != G2->getAlignment())
1151 return Error(ErrorMsg,
1152 "Appending variables with different alignment need to be linked!");
1153
1154 if (G1->getVisibility() != G2->getVisibility())
1155 return Error(ErrorMsg,
1156 "Appending variables with different visibility need to be linked!");
1157
1158 if (G1->getSection() != G2->getSection())
1159 return Error(ErrorMsg,
1160 "Appending variables with different section name need to be linked!");
1161
1162 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1163 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1164
1165 G1->setName(""); // Clear G1's name in case of a conflict!
1166
1167 // Create the new global variable...
1168 GlobalVariable *NG =
1169 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
1170 /*init*/0, First->first, M, G1->isThreadLocal());
1171
1172 // Propagate alignment, visibility and section info.
1173 CopyGVAttributes(NG, G1);
1174
1175 // Merge the initializer...
1176 Inits.reserve(NewSize);
1177 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1178 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1179 Inits.push_back(I->getOperand(i));
1180 } else {
1181 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1182 Constant *CV = Constant::getNullValue(T1->getElementType());
1183 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1184 Inits.push_back(CV);
1185 }
1186 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1187 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1188 Inits.push_back(I->getOperand(i));
1189 } else {
1190 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1191 Constant *CV = Constant::getNullValue(T2->getElementType());
1192 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1193 Inits.push_back(CV);
1194 }
1195 NG->setInitializer(ConstantArray::get(NewType, Inits));
1196 Inits.clear();
1197
1198 // Replace any uses of the two global variables with uses of the new
1199 // global...
1200
1201 // FIXME: This should rewrite simple/straight-forward uses such as
1202 // getelementptr instructions to not use the Cast!
1203 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1204 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
1205
1206 // Remove the two globals from the module now...
1207 M->getGlobalList().erase(G1);
1208 M->getGlobalList().erase(G2);
1209
1210 // Put the new global into the AppendingVars map so that we can handle
1211 // linking of more than two vars...
1212 Second->second = NG;
1213 }
1214 AppendingVars.erase(First);
1215 }
1216
1217 return false;
1218}
1219
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001220static bool ResolveAliases(Module *Dest) {
1221 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov82192622008-03-11 22:51:09 +00001222 I != E; ++I)
1223 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1224 if (!GV->isDeclaration())
1225 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001226
1227 return false;
1228}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229
1230// LinkModules - This function links two modules together, with the resulting
1231// left module modified to be the composite of the two input modules. If an
1232// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1233// the problem. Upon failure, the Dest module could be in a modified state, and
1234// shouldn't be relied on to be consistent.
1235bool
1236Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1237 assert(Dest != 0 && "Invalid Destination module");
1238 assert(Src != 0 && "Invalid Source Module");
1239
1240 if (Dest->getDataLayout().empty()) {
1241 if (!Src->getDataLayout().empty()) {
1242 Dest->setDataLayout(Src->getDataLayout());
1243 } else {
1244 std::string DataLayout;
1245
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001246 if (Dest->getEndianness() == Module::AnyEndianness) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 if (Src->getEndianness() == Module::BigEndian)
1248 DataLayout.append("E");
1249 else if (Src->getEndianness() == Module::LittleEndian)
1250 DataLayout.append("e");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001251 }
1252
1253 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 if (Src->getPointerSize() == Module::Pointer64)
1255 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1256 else if (Src->getPointerSize() == Module::Pointer32)
1257 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001258 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 Dest->setDataLayout(DataLayout);
1260 }
1261 }
1262
Chris Lattner85dd49c2008-02-19 18:49:08 +00001263 // Copy the target triple from the source to dest if the dest's is empty.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1265 Dest->setTargetTriple(Src->getTargetTriple());
1266
1267 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1268 Src->getDataLayout() != Dest->getDataLayout())
1269 cerr << "WARNING: Linking two modules of different data layouts!\n";
1270 if (!Src->getTargetTriple().empty() &&
1271 Dest->getTargetTriple() != Src->getTargetTriple())
1272 cerr << "WARNING: Linking two modules of different target triples!\n";
1273
Chris Lattner85dd49c2008-02-19 18:49:08 +00001274 // Append the module inline asm string.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 if (!Src->getModuleInlineAsm().empty()) {
1276 if (Dest->getModuleInlineAsm().empty())
1277 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1278 else
1279 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1280 Src->getModuleInlineAsm());
1281 }
1282
1283 // Update the destination module's dependent libraries list with the libraries
1284 // from the source module. There's no opportunity for duplicates here as the
1285 // Module ensures that duplicate insertions are discarded.
Chris Lattner85dd49c2008-02-19 18:49:08 +00001286 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1287 SI != SE; ++SI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 Dest->addLibrary(*SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289
1290 // LinkTypes - Go through the symbol table of the Src module and see if any
1291 // types are named in the src module that are not named in the Dst module.
1292 // Make sure there are no type name conflicts.
1293 if (LinkTypes(Dest, Src, ErrorMsg))
1294 return true;
1295
1296 // ValueMap - Mapping of values from what they used to be in Src, to what they
1297 // are now in Dest.
1298 std::map<const Value*, Value*> ValueMap;
1299
1300 // AppendingVars - Keep track of global variables in the destination module
1301 // with appending linkage. After the module is linked together, they are
1302 // appended and the module is rewritten.
1303 std::multimap<std::string, GlobalVariable *> AppendingVars;
1304 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1305 I != E; ++I) {
1306 // Add all of the appending globals already in the Dest module to
1307 // AppendingVars.
1308 if (I->hasAppendingLinkage())
1309 AppendingVars.insert(std::make_pair(I->getName(), I));
1310 }
1311
1312 // Insert all of the globals in src into the Dest module... without linking
1313 // initializers (which could refer to functions not yet mapped over).
1314 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1315 return true;
1316
1317 // Link the functions together between the two modules, without doing function
1318 // bodies... this just adds external function prototypes to the Dest
1319 // function... We do this so that when we begin processing function bodies,
1320 // all of the global values that may be referenced are available in our
1321 // ValueMap.
1322 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1323 return true;
1324
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +00001325 // If there were any alias, link them now. We really need to do this now,
1326 // because all of the aliases that may be referenced need to be available in
1327 // ValueMap
1328 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1329
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 // Update the initializers in the Dest module now that all globals that may
1331 // be referenced are in Dest.
1332 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1333
1334 // Link in the function bodies that are defined in the source module into the
1335 // DestModule. This consists basically of copying the function over and
1336 // fixing up references to values.
1337 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1338
1339 // If there were any appending global variables, link them together now.
1340 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1341
Anton Korobeynikova68796c2008-03-05 23:08:47 +00001342 // Resolve all uses of aliases with aliasees
1343 if (ResolveAliases(Dest)) return true;
1344
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 // If the source library's module id is in the dependent library list of the
1346 // destination library, remove it since that module is now linked in.
1347 sys::Path modId;
1348 modId.set(Src->getModuleIdentifier());
1349 if (!modId.isEmpty())
1350 Dest->removeLibrary(modId.getBasename());
1351
1352 return false;
1353}
1354
1355// vim: sw=2