blob: 433dfa682d60d02c0d7472620243b029856da663 [file] [log] [blame]
Reid Spencer361e5132004-11-12 20:37:43 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Reid Spencer361e5132004-11-12 20:37:43 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Reid Spencer361e5132004-11-12 20:37:43 +00008//===----------------------------------------------------------------------===//
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
Reid Spencer9b0ddbb2004-11-14 23:27:04 +000019#include "llvm/Linker.h"
Reid Spencer361e5132004-11-12 20:37:43 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Module.h"
23#include "llvm/SymbolTable.h"
24#include "llvm/Instructions.h"
25#include "llvm/Assembly/Writer.h"
Bill Wendling7339b8d2006-11-27 10:09:12 +000026#include "llvm/Support/Streams.h"
Reid Spencer361e5132004-11-12 20:37:43 +000027#include "llvm/System/Path.h"
Bill Wendling30c0f332006-12-07 23:41:45 +000028#include <sstream>
Reid Spencer361e5132004-11-12 20:37:43 +000029using namespace llvm;
30
31// Error - Simple wrapper function to conditionally assign to E and return true.
32// This just makes error return conditions a little bit simpler...
Reid Spencer361e5132004-11-12 20:37:43 +000033static inline bool Error(std::string *E, const std::string &Message) {
34 if (E) *E = Message;
35 return true;
36}
37
Reid Spencer2c4f9a42004-11-25 09:29:44 +000038// ToStr - Simple wrapper function to convert a type to a string.
Reid Spencer361e5132004-11-12 20:37:43 +000039static std::string ToStr(const Type *Ty, const Module *M) {
40 std::ostringstream OS;
41 WriteTypeSymbolic(OS, Ty, M);
42 return OS.str();
43}
44
45//
46// Function: ResolveTypes()
47//
48// Description:
49// Attempt to link the two specified types together.
50//
51// Inputs:
52// DestTy - The type to which we wish to resolve.
53// SrcTy - The original type which we want to resolve.
54// Name - The name of the type.
55//
56// Outputs:
57// DestST - The symbol table in which the new type should be placed.
58//
59// Return value:
60// true - There is an error and the types cannot yet be linked.
61// false - No errors.
62//
63static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
64 SymbolTable *DestST, const std::string &Name) {
65 if (DestTy == SrcTy) return false; // If already equal, noop
66
67 // Does the type already exist in the module?
68 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
69 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
71 } else {
72 return true; // Cannot link types... neither is opaque and not-equal
73 }
74 } else { // Type not in dest module. Add it now.
75 if (DestTy) // Type _is_ in module, just opaque...
76 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77 ->refineAbstractTypeTo(SrcTy);
78 else if (!Name.empty())
79 DestST->insert(Name, const_cast<Type*>(SrcTy));
80 }
81 return false;
82}
83
84static const FunctionType *getFT(const PATypeHolder &TH) {
85 return cast<FunctionType>(TH.get());
86}
87static const StructType *getST(const PATypeHolder &TH) {
88 return cast<StructType>(TH.get());
89}
90
91// RecursiveResolveTypes - This is just like ResolveTypes, except that it
92// recurses down into derived types, merging the used types if the parent types
93// are compatible.
Reid Spencer361e5132004-11-12 20:37:43 +000094static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
95 const PATypeHolder &SrcTy,
96 SymbolTable *DestST, const std::string &Name,
97 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
98 const Type *SrcTyT = SrcTy.get();
99 const Type *DestTyT = DestTy.get();
100 if (DestTyT == SrcTyT) return false; // If already equal, noop
Misha Brukman10468d82005-04-21 22:55:34 +0000101
Reid Spencer361e5132004-11-12 20:37:43 +0000102 // If we found our opaque type, resolve it now!
103 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
104 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Misha Brukman10468d82005-04-21 22:55:34 +0000105
Reid Spencer361e5132004-11-12 20:37:43 +0000106 // Two types cannot be resolved together if they are of different primitive
107 // type. For example, we cannot resolve an int to a float.
108 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
109
110 // Otherwise, resolve the used type used by this derived type...
111 switch (DestTyT->getTypeID()) {
112 case Type::FunctionTyID: {
113 if (cast<FunctionType>(DestTyT)->isVarArg() !=
114 cast<FunctionType>(SrcTyT)->isVarArg() ||
115 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
116 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
117 return true;
118 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
119 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
120 getFT(SrcTy)->getContainedType(i), DestST, "",
121 Pointers))
122 return true;
123 return false;
124 }
125 case Type::StructTyID: {
Misha Brukman10468d82005-04-21 22:55:34 +0000126 if (getST(DestTy)->getNumContainedTypes() !=
Reid Spencer361e5132004-11-12 20:37:43 +0000127 getST(SrcTy)->getNumContainedTypes()) return 1;
128 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
129 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
130 getST(SrcTy)->getContainedType(i), DestST, "",
131 Pointers))
132 return true;
133 return false;
134 }
135 case Type::ArrayTyID: {
136 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
137 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
138 if (DAT->getNumElements() != SAT->getNumElements()) return true;
139 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
140 DestST, "", Pointers);
141 }
142 case Type::PointerTyID: {
143 // If this is a pointer type, check to see if we have already seen it. If
144 // so, we are in a recursive branch. Cut off the search now. We cannot use
145 // an associative container for this search, because the type pointers (keys
146 // in the container) change whenever types get resolved...
Reid Spencer361e5132004-11-12 20:37:43 +0000147 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
148 if (Pointers[i].first == DestTy)
149 return Pointers[i].second != SrcTy;
150
151 // Otherwise, add the current pointers to the vector to stop recursion on
152 // this pair.
153 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
154 bool Result =
155 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
156 cast<PointerType>(SrcTy.get())->getElementType(),
157 DestST, "", Pointers);
158 Pointers.pop_back();
159 return Result;
160 }
161 default: assert(0 && "Unexpected type!"); return true;
Misha Brukman10468d82005-04-21 22:55:34 +0000162 }
Reid Spencer361e5132004-11-12 20:37:43 +0000163}
164
165static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
166 const PATypeHolder &SrcTy,
167 SymbolTable *DestST, const std::string &Name){
168 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
169 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
170}
171
172
173// LinkTypes - Go through the symbol table of the Src module and see if any
174// types are named in the src module that are not named in the Dst module.
175// Make sure there are no type name conflicts.
Reid Spencer361e5132004-11-12 20:37:43 +0000176static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
177 SymbolTable *DestST = &Dest->getSymbolTable();
178 const SymbolTable *SrcST = &Src->getSymbolTable();
179
180 // Look for a type plane for Type's...
181 SymbolTable::type_const_iterator TI = SrcST->type_begin();
182 SymbolTable::type_const_iterator TE = SrcST->type_end();
183 if (TI == TE) return false; // No named types, do nothing.
184
185 // Some types cannot be resolved immediately because they depend on other
186 // types being resolved to each other first. This contains a list of types we
187 // are waiting to recheck.
188 std::vector<std::string> DelayedTypesToResolve;
189
190 for ( ; TI != TE; ++TI ) {
191 const std::string &Name = TI->first;
192 const Type *RHS = TI->second;
193
194 // Check to see if this type name is already in the dest module...
195 Type *Entry = DestST->lookupType(Name);
196
197 if (ResolveTypes(Entry, RHS, DestST, Name)) {
198 // They look different, save the types 'till later to resolve.
199 DelayedTypesToResolve.push_back(Name);
200 }
201 }
202
203 // Iteratively resolve types while we can...
204 while (!DelayedTypesToResolve.empty()) {
205 // Loop over all of the types, attempting to resolve them if possible...
206 unsigned OldSize = DelayedTypesToResolve.size();
207
208 // Try direct resolution by name...
209 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
210 const std::string &Name = DelayedTypesToResolve[i];
211 Type *T1 = SrcST->lookupType(Name);
212 Type *T2 = DestST->lookupType(Name);
213 if (!ResolveTypes(T2, T1, DestST, Name)) {
214 // We are making progress!
215 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
216 --i;
217 }
218 }
219
220 // Did we not eliminate any types?
221 if (DelayedTypesToResolve.size() == OldSize) {
222 // Attempt to resolve subelements of types. This allows us to merge these
223 // two types: { int* } and { opaque* }
224 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
225 const std::string &Name = DelayedTypesToResolve[i];
226 PATypeHolder T1(SrcST->lookupType(Name));
227 PATypeHolder T2(DestST->lookupType(Name));
228
229 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
230 // We are making progress!
231 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukman10468d82005-04-21 22:55:34 +0000232
Reid Spencer361e5132004-11-12 20:37:43 +0000233 // Go back to the main loop, perhaps we can resolve directly by name
234 // now...
235 break;
236 }
237 }
238
239 // If we STILL cannot resolve the types, then there is something wrong.
Reid Spencer361e5132004-11-12 20:37:43 +0000240 if (DelayedTypesToResolve.size() == OldSize) {
Reid Spencer361e5132004-11-12 20:37:43 +0000241 // Remove the symbol name from the destination.
242 DelayedTypesToResolve.pop_back();
243 }
244 }
245 }
246
247
248 return false;
249}
250
251static void PrintMap(const std::map<const Value*, Value*> &M) {
252 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
253 I != E; ++I) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000254 cerr << " Fr: " << (void*)I->first << " ";
Reid Spencer361e5132004-11-12 20:37:43 +0000255 I->first->dump();
Bill Wendlingf3baad32006-12-07 01:30:32 +0000256 cerr << " To: " << (void*)I->second << " ";
Reid Spencer361e5132004-11-12 20:37:43 +0000257 I->second->dump();
Bill Wendlingf3baad32006-12-07 01:30:32 +0000258 cerr << "\n";
Reid Spencer361e5132004-11-12 20:37:43 +0000259 }
260}
261
262
Chris Lattner7391dde2004-11-16 17:12:38 +0000263// RemapOperand - Use ValueMap to convert references from one module to another.
264// This is somewhat sophisticated in that it can automatically handle constant
Chris Lattnerc7745922006-06-01 19:14:22 +0000265// references correctly as well.
Reid Spencer361e5132004-11-12 20:37:43 +0000266static Value *RemapOperand(const Value *In,
Chris Lattner7391dde2004-11-16 17:12:38 +0000267 std::map<const Value*, Value*> &ValueMap) {
268 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
269 if (I != ValueMap.end()) return I->second;
Reid Spencer361e5132004-11-12 20:37:43 +0000270
Chris Lattner7391dde2004-11-16 17:12:38 +0000271 // Check to see if it's a constant that we are interesting in transforming.
Chris Lattnerc7745922006-06-01 19:14:22 +0000272 Value *Result = 0;
Reid Spencer361e5132004-11-12 20:37:43 +0000273 if (const Constant *CPV = dyn_cast<Constant>(In)) {
274 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
275 isa<ConstantAggregateZero>(CPV))
Chris Lattner7391dde2004-11-16 17:12:38 +0000276 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Reid Spencer361e5132004-11-12 20:37:43 +0000277
Reid Spencer361e5132004-11-12 20:37:43 +0000278 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
279 std::vector<Constant*> Operands(CPA->getNumOperands());
280 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner7391dde2004-11-16 17:12:38 +0000281 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000282 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
283 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
284 std::vector<Constant*> Operands(CPS->getNumOperands());
285 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner7391dde2004-11-16 17:12:38 +0000286 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000287 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
288 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
289 Result = const_cast<Constant*>(CPV);
290 } else if (isa<GlobalValue>(CPV)) {
Chris Lattner7391dde2004-11-16 17:12:38 +0000291 Result = cast<Constant>(RemapOperand(CPV, ValueMap));
Chris Lattner93bde9c2006-01-19 23:15:58 +0000292 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CPV)) {
293 std::vector<Constant*> Operands(CP->getNumOperands());
294 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
295 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
296 Result = ConstantPacked::get(Operands);
Reid Spencer361e5132004-11-12 20:37:43 +0000297 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner19247f32006-07-14 22:21:31 +0000298 std::vector<Constant*> Ops;
299 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
300 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
301 Result = CE->getWithOperands(Ops);
Reid Spencer361e5132004-11-12 20:37:43 +0000302 } else {
303 assert(0 && "Unknown type of derived type constant value!");
304 }
Chris Lattnerc7745922006-06-01 19:14:22 +0000305 } else if (isa<InlineAsm>(In)) {
306 Result = const_cast<Value*>(In);
307 }
308
309 // Cache the mapping in our local map structure...
310 if (Result) {
Chris Lattner7391dde2004-11-16 17:12:38 +0000311 ValueMap.insert(std::make_pair(In, Result));
Reid Spencer361e5132004-11-12 20:37:43 +0000312 return Result;
313 }
Chris Lattnerc7745922006-06-01 19:14:22 +0000314
Reid Spencer361e5132004-11-12 20:37:43 +0000315
Bill Wendlingf3baad32006-12-07 01:30:32 +0000316 cerr << "LinkModules ValueMap: \n";
Chris Lattner7391dde2004-11-16 17:12:38 +0000317 PrintMap(ValueMap);
Reid Spencer361e5132004-11-12 20:37:43 +0000318
Bill Wendlingf3baad32006-12-07 01:30:32 +0000319 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Reid Spencer361e5132004-11-12 20:37:43 +0000320 assert(0 && "Couldn't remap value!");
321 return 0;
322}
323
324/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
325/// in the symbol table. This is good for all clients except for us. Go
326/// through the trouble to force this back.
327static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
328 assert(GV->getName() != Name && "Can't force rename to self");
329 SymbolTable &ST = GV->getParent()->getSymbolTable();
330
331 // If there is a conflict, rename the conflict.
332 Value *ConflictVal = ST.lookup(GV->getType(), Name);
333 assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
334 GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
335 assert(ConflictGV->hasInternalLinkage() &&
336 "Not conflicting with a static global, should link instead!");
337
338 ConflictGV->setName(""); // Eliminate the conflict
339 GV->setName(Name); // Force the name back
340 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
341 assert(GV->getName() == Name && ConflictGV->getName() != Name &&
342 "ForceRenaming didn't work");
343}
344
Chris Lattnerfc61de32004-12-03 22:18:41 +0000345/// GetLinkageResult - This analyzes the two global values and determines what
346/// the result will look like in the destination module. In particular, it
347/// computes the resultant linkage type, computes whether the global in the
348/// source should be copied over to the destination (replacing the existing
349/// one), and computes whether this linkage is an error or not.
350static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
351 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
352 std::string *Err) {
353 assert((!Dest || !Src->hasInternalLinkage()) &&
354 "If Src has internal linkage, Dest shouldn't be set!");
355 if (!Dest) {
356 // Linking something to nothing.
357 LinkFromSrc = true;
358 LT = Src->getLinkage();
359 } else if (Src->isExternal()) {
360 // If Src is external or if both Src & Drc are external.. Just link the
361 // external globals, we aren't adding anything.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000362 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000363 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000364 if (Dest->isExternal()) {
365 LinkFromSrc = true;
366 LT = Src->getLinkage();
367 }
368 } else {
369 LinkFromSrc = false;
370 LT = Dest->getLinkage();
371 }
372 } else if (Dest->isExternal() && !Dest->hasDLLImportLinkage()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000373 // If Dest is external but Src is not:
374 LinkFromSrc = true;
375 LT = Src->getLinkage();
376 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
377 if (Src->getLinkage() != Dest->getLinkage())
378 return Error(Err, "Linking globals named '" + Src->getName() +
379 "': can only link appending global with another appending global!");
380 LinkFromSrc = true; // Special cased.
381 LT = Src->getLinkage();
382 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000383 // At this point we know that Dest has LinkOnce, External*, Weak, DLL* linkage.
384 if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
385 Dest->hasExternalWeakLinkage()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000386 LinkFromSrc = true;
387 LT = Src->getLinkage();
388 } else {
389 LinkFromSrc = false;
390 LT = Dest->getLinkage();
391 }
392 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000393 // At this point we know that Src has External* or DLL* linkage.
394 if (Src->hasExternalWeakLinkage()) {
395 LinkFromSrc = false;
396 LT = Dest->getLinkage();
397 } else {
398 LinkFromSrc = true;
399 LT = GlobalValue::ExternalLinkage;
400 }
Chris Lattnerfc61de32004-12-03 22:18:41 +0000401 } else {
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000402 assert((Dest->hasExternalLinkage() ||
403 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000404 Dest->hasDLLExportLinkage() ||
405 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000406 (Src->hasExternalLinkage() ||
407 Src->hasDLLImportLinkage() ||
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000408 Src->hasDLLExportLinkage() ||
409 Src->hasExternalWeakLinkage()) &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000410 "Unexpected linkage type!");
Misha Brukman10468d82005-04-21 22:55:34 +0000411 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000412 "': symbol multiply defined!");
413 }
414 return false;
415}
Reid Spencer361e5132004-11-12 20:37:43 +0000416
417// LinkGlobals - Loop through the global variables in the src module and merge
418// them into the dest module.
Chris Lattnerfc61de32004-12-03 22:18:41 +0000419static bool LinkGlobals(Module *Dest, Module *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000420 std::map<const Value*, Value*> &ValueMap,
421 std::multimap<std::string, GlobalVariable *> &AppendingVars,
422 std::map<std::string, GlobalValue*> &GlobalsByName,
423 std::string *Err) {
424 // We will need a module level symbol table if the src module has a module
425 // level symbol table...
426 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukman10468d82005-04-21 22:55:34 +0000427
Reid Spencer361e5132004-11-12 20:37:43 +0000428 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000429 for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
430 I != E; ++I) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000431 GlobalVariable *SGV = I;
Reid Spencer361e5132004-11-12 20:37:43 +0000432 GlobalVariable *DGV = 0;
433 // Check to see if may have to link the global.
434 if (SGV->hasName() && !SGV->hasInternalLinkage())
435 if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
436 SGV->getType()->getElementType()))) {
437 std::map<std::string, GlobalValue*>::iterator EGV =
438 GlobalsByName.find(SGV->getName());
439 if (EGV != GlobalsByName.end())
440 DGV = dyn_cast<GlobalVariable>(EGV->second);
Chris Lattnerfc61de32004-12-03 22:18:41 +0000441 if (DGV)
442 // If types don't agree due to opaque types, try to resolve them.
443 RecursiveResolveTypes(SGV->getType(), DGV->getType(),ST, "");
Reid Spencer361e5132004-11-12 20:37:43 +0000444 }
445
Chris Lattnerfc61de32004-12-03 22:18:41 +0000446 if (DGV && DGV->hasInternalLinkage())
447 DGV = 0;
448
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000449 assert(SGV->hasInitializer() ||
450 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage() &&
Reid Spencer361e5132004-11-12 20:37:43 +0000451 "Global must either be external or have an initializer!");
452
Chris Lattner1b9633d2006-11-09 05:18:12 +0000453 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
454 bool LinkFromSrc = false;
Chris Lattnerfc61de32004-12-03 22:18:41 +0000455 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
456 return true;
Reid Spencer361e5132004-11-12 20:37:43 +0000457
Chris Lattnerfc61de32004-12-03 22:18:41 +0000458 if (!DGV) {
Reid Spencer361e5132004-11-12 20:37:43 +0000459 // No linking to be performed, simply create an identical version of the
460 // symbol over in the dest module... the initializer will be filled in
461 // later by LinkGlobalInits...
Reid Spencer361e5132004-11-12 20:37:43 +0000462 GlobalVariable *NewDGV =
463 new GlobalVariable(SGV->getType()->getElementType(),
464 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
465 SGV->getName(), Dest);
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000466 // Propagate alignment info.
467 NewDGV->setAlignment(SGV->getAlignment());
468
Reid Spencer361e5132004-11-12 20:37:43 +0000469 // If the LLVM runtime renamed the global, but it is an externally visible
470 // symbol, DGV must be an existing global with internal linkage. Rename
471 // it.
472 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
473 ForceRenaming(NewDGV, SGV->getName());
474
475 // Make sure to remember this mapping...
476 ValueMap.insert(std::make_pair(SGV, NewDGV));
477 if (SGV->hasAppendingLinkage())
478 // Keep track that this is an appending variable...
479 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattnerfc61de32004-12-03 22:18:41 +0000480 } else if (DGV->hasAppendingLinkage()) {
Reid Spencer361e5132004-11-12 20:37:43 +0000481 // No linking is performed yet. Just insert a new copy of the global, and
482 // keep track of the fact that it is an appending variable in the
483 // AppendingVars map. The name is cleared out so that no linkage is
484 // performed.
485 GlobalVariable *NewDGV =
486 new GlobalVariable(SGV->getType()->getElementType(),
487 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
488 "", Dest);
489
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000490 // Propagate alignment info.
491 NewDGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
492
Reid Spencer361e5132004-11-12 20:37:43 +0000493 // Make sure to remember this mapping...
494 ValueMap.insert(std::make_pair(SGV, NewDGV));
495
496 // Keep track that this is an appending variable...
497 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
498 } else {
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000499 // Propagate alignment info.
500 DGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
501
Chris Lattnerfc61de32004-12-03 22:18:41 +0000502 // Otherwise, perform the mapping as instructed by GetLinkageResult. If
503 // the types don't match, and if we are to link from the source, nuke DGV
504 // and create a new one of the appropriate type.
505 if (SGV->getType() != DGV->getType() && LinkFromSrc) {
506 GlobalVariable *NewDGV =
507 new GlobalVariable(SGV->getType()->getElementType(),
508 DGV->isConstant(), DGV->getLinkage());
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000509 NewDGV->setAlignment(DGV->getAlignment());
Chris Lattnerfc61de32004-12-03 22:18:41 +0000510 Dest->getGlobalList().insert(DGV, NewDGV);
Reid Spencerb341b082006-12-12 05:05:00 +0000511 DGV->replaceAllUsesWith(
512 ConstantExpr::getBitCast(NewDGV, DGV->getType()));
Chris Lattnerfc61de32004-12-03 22:18:41 +0000513 DGV->eraseFromParent();
514 NewDGV->setName(SGV->getName());
515 DGV = NewDGV;
516 }
517
518 DGV->setLinkage(NewLinkage);
519
520 if (LinkFromSrc) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000521 // Inherit const as appropriate
Chris Lattner16277c12005-02-12 19:20:28 +0000522 DGV->setConstant(SGV->isConstant());
Chris Lattnerfc61de32004-12-03 22:18:41 +0000523 DGV->setInitializer(0);
524 } else {
525 if (SGV->isConstant() && !DGV->isConstant()) {
Chris Lattner16277c12005-02-12 19:20:28 +0000526 if (DGV->isExternal())
Chris Lattnerfc61de32004-12-03 22:18:41 +0000527 DGV->setConstant(true);
528 }
Chris Lattnera57c1052004-12-04 18:54:48 +0000529 SGV->setLinkage(GlobalValue::ExternalLinkage);
530 SGV->setInitializer(0);
Chris Lattnerfc61de32004-12-03 22:18:41 +0000531 }
532
Reid Spencerb341b082006-12-12 05:05:00 +0000533 ValueMap.insert(
534 std::make_pair(SGV, ConstantExpr::getBitCast(DGV, SGV->getType())));
Reid Spencer361e5132004-11-12 20:37:43 +0000535 }
536 }
537 return false;
538}
539
540
541// LinkGlobalInits - Update the initializers in the Dest module now that all
542// globals that may be referenced are in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000543static bool LinkGlobalInits(Module *Dest, const Module *Src,
544 std::map<const Value*, Value*> &ValueMap,
545 std::string *Err) {
546
547 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000548 for (Module::const_global_iterator I = Src->global_begin(),
549 E = Src->global_end(); I != E; ++I) {
Reid Spencer361e5132004-11-12 20:37:43 +0000550 const GlobalVariable *SGV = I;
551
552 if (SGV->hasInitializer()) { // Only process initialized GV's
553 // Figure out what the initializer looks like in the dest module...
554 Constant *SInit =
Chris Lattner7391dde2004-11-16 17:12:38 +0000555 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000556
Misha Brukman10468d82005-04-21 22:55:34 +0000557 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Reid Spencer361e5132004-11-12 20:37:43 +0000558 if (DGV->hasInitializer()) {
559 if (SGV->hasExternalLinkage()) {
560 if (DGV->getInitializer() != SInit)
Misha Brukman10468d82005-04-21 22:55:34 +0000561 return Error(Err, "Global Variable Collision on '" +
Reid Spencer361e5132004-11-12 20:37:43 +0000562 ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
563 " - Global variables have different initializers");
564 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
565 // Nothing is required, mapped values will take the new global
566 // automatically.
567 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
568 // Nothing is required, mapped values will take the new global
569 // automatically.
570 } else if (DGV->hasAppendingLinkage()) {
571 assert(0 && "Appending linkage unimplemented!");
572 } else {
573 assert(0 && "Unknown linkage!");
574 }
575 } else {
576 // Copy the initializer over now...
577 DGV->setInitializer(SInit);
578 }
579 }
580 }
581 return false;
582}
583
584// LinkFunctionProtos - Link the functions together between the two modules,
585// without doing function bodies... this just adds external function prototypes
586// to the Dest function...
587//
588static bool LinkFunctionProtos(Module *Dest, const Module *Src,
589 std::map<const Value*, Value*> &ValueMap,
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000590 std::map<std::string, GlobalValue*> &GlobalsByName,
Reid Spencer361e5132004-11-12 20:37:43 +0000591 std::string *Err) {
592 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukman10468d82005-04-21 22:55:34 +0000593
Reid Spencer361e5132004-11-12 20:37:43 +0000594 // Loop over all of the functions in the src module, mapping them over as we
595 // go
Reid Spencer361e5132004-11-12 20:37:43 +0000596 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
597 const Function *SF = I; // SrcFunction
598 Function *DF = 0;
599 if (SF->hasName() && !SF->hasInternalLinkage()) {
600 // Check to see if may have to link the function.
601 if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
602 std::map<std::string, GlobalValue*>::iterator EF =
603 GlobalsByName.find(SF->getName());
604 if (EF != GlobalsByName.end())
605 DF = dyn_cast<Function>(EF->second);
606 if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
607 DF = 0; // FIXME: gross.
608 }
609 }
610
611 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
612 // Function does not already exist, simply insert an function signature
613 // identical to SF into the dest module...
614 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
615 SF->getName(), Dest);
Chris Lattnere251b5c2005-05-09 01:09:39 +0000616 NewDF->setCallingConv(SF->getCallingConv());
Reid Spencer361e5132004-11-12 20:37:43 +0000617
618 // If the LLVM runtime renamed the function, but it is an externally
619 // visible symbol, DF must be an existing function with internal linkage.
620 // Rename it.
621 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
622 ForceRenaming(NewDF, SF->getName());
623
624 // ... and remember this mapping...
625 ValueMap.insert(std::make_pair(SF, NewDF));
626 } else if (SF->isExternal()) {
627 // If SF is external or if both SF & DF are external.. Just link the
628 // external functions, we aren't adding anything.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000629 if (SF->hasDLLImportLinkage()) {
630 if (DF->isExternal()) {
631 ValueMap.insert(std::make_pair(SF, DF));
632 DF->setLinkage(SF->getLinkage());
633 }
634 } else {
635 ValueMap.insert(std::make_pair(SF, DF));
636 }
637 } else if (DF->isExternal() && !DF->hasDLLImportLinkage()) {
638 // If DF is external but SF is not...
Reid Spencer361e5132004-11-12 20:37:43 +0000639 // Link the external functions, update linkage qualifiers
640 ValueMap.insert(std::make_pair(SF, DF));
641 DF->setLinkage(SF->getLinkage());
Reid Spencer361e5132004-11-12 20:37:43 +0000642 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000643 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
Reid Spencer361e5132004-11-12 20:37:43 +0000644 ValueMap.insert(std::make_pair(SF, DF));
645
646 // Linkonce+Weak = Weak
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000647 // *+External Weak = *
648 if ((DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) ||
649 DF->hasExternalWeakLinkage())
Reid Spencer361e5132004-11-12 20:37:43 +0000650 DF->setLinkage(SF->getLinkage());
651
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000652
Reid Spencer361e5132004-11-12 20:37:43 +0000653 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000654 // At this point we know that SF has LinkOnce or External* linkage.
Reid Spencer361e5132004-11-12 20:37:43 +0000655 ValueMap.insert(std::make_pair(SF, DF));
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000656 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage())
657 // Don't inherit linkonce & external weak linkage
Reid Spencer361e5132004-11-12 20:37:43 +0000658 DF->setLinkage(SF->getLinkage());
Reid Spencer361e5132004-11-12 20:37:43 +0000659 } else if (SF->getLinkage() != DF->getLinkage()) {
660 return Error(Err, "Functions named '" + SF->getName() +
661 "' have different linkage specifiers!");
662 } else if (SF->hasExternalLinkage()) {
663 // The function is defined in both modules!!
Misha Brukman10468d82005-04-21 22:55:34 +0000664 return Error(Err, "Function '" +
665 ToStr(SF->getFunctionType(), Src) + "':\"" +
Reid Spencer361e5132004-11-12 20:37:43 +0000666 SF->getName() + "\" - Function is already defined!");
667 } else {
668 assert(0 && "Unknown linkage configuration found!");
669 }
670 }
671 return false;
672}
673
674// LinkFunctionBody - Copy the source function over into the dest function and
675// fix up references to values. At this point we know that Dest is an external
676// function, and that Src is not.
Chris Lattner2f0557d2004-11-16 07:31:51 +0000677static bool LinkFunctionBody(Function *Dest, Function *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000678 std::map<const Value*, Value*> &GlobalMap,
679 std::string *Err) {
680 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Reid Spencer361e5132004-11-12 20:37:43 +0000681
Chris Lattner7391dde2004-11-16 17:12:38 +0000682 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner531f9e92005-03-15 04:54:21 +0000683 Function::arg_iterator DI = Dest->arg_begin();
684 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +0000685 I != E; ++I, ++DI) {
686 DI->setName(I->getName()); // Copy the name information over...
687
688 // Add a mapping to our local map
Chris Lattner7391dde2004-11-16 17:12:38 +0000689 GlobalMap.insert(std::make_pair(I, DI));
Reid Spencer361e5132004-11-12 20:37:43 +0000690 }
691
Chris Lattner2f0557d2004-11-16 07:31:51 +0000692 // Splice the body of the source function into the dest function.
693 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Reid Spencer361e5132004-11-12 20:37:43 +0000694
695 // At this point, all of the instructions and values of the function are now
696 // copied over. The only problem is that they are still referencing values in
697 // the Source function as operands. Loop through all of the operands of the
698 // functions and patch them up to point to the local versions...
699 //
700 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
701 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
702 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
703 OI != OE; ++OI)
Chris Lattner2f0557d2004-11-16 07:31:51 +0000704 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner7391dde2004-11-16 17:12:38 +0000705 *OI = RemapOperand(*OI, GlobalMap);
706
707 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000708 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
709 I != E; ++I)
Chris Lattner7391dde2004-11-16 17:12:38 +0000710 GlobalMap.erase(I);
Reid Spencer361e5132004-11-12 20:37:43 +0000711
712 return false;
713}
714
715
716// LinkFunctionBodies - Link in the function bodies that are defined in the
717// source module into the DestModule. This consists basically of copying the
718// function over and fixing up references to values.
Chris Lattner2f0557d2004-11-16 07:31:51 +0000719static bool LinkFunctionBodies(Module *Dest, Module *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000720 std::map<const Value*, Value*> &ValueMap,
721 std::string *Err) {
722
723 // Loop over all of the functions in the src module, mapping them over as we
724 // go
Chris Lattner2f0557d2004-11-16 07:31:51 +0000725 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer361e5132004-11-12 20:37:43 +0000726 if (!SF->isExternal()) { // No body if function is external
727 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
728
729 // DF not external SF external?
730 if (DF->isExternal()) {
731 // Only provide the function body if there isn't one already.
732 if (LinkFunctionBody(DF, SF, ValueMap, Err))
733 return true;
734 }
735 }
736 }
737 return false;
738}
739
740// LinkAppendingVars - If there were any appending global variables, link them
741// together now. Return true on error.
Reid Spencer361e5132004-11-12 20:37:43 +0000742static bool LinkAppendingVars(Module *M,
743 std::multimap<std::string, GlobalVariable *> &AppendingVars,
744 std::string *ErrorMsg) {
745 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukman10468d82005-04-21 22:55:34 +0000746
Reid Spencer361e5132004-11-12 20:37:43 +0000747 // Loop over the multimap of appending vars, processing any variables with the
748 // same name, forming a new appending global variable with both of the
749 // initializers merged together, then rewrite references to the old variables
750 // and delete them.
Reid Spencer361e5132004-11-12 20:37:43 +0000751 std::vector<Constant*> Inits;
752 while (AppendingVars.size() > 1) {
753 // Get the first two elements in the map...
754 std::multimap<std::string,
755 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
756
757 // If the first two elements are for different names, there is no pair...
758 // Otherwise there is a pair, so link them together...
759 if (First->first == Second->first) {
760 GlobalVariable *G1 = First->second, *G2 = Second->second;
761 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
762 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukman10468d82005-04-21 22:55:34 +0000763
Reid Spencer361e5132004-11-12 20:37:43 +0000764 // Check to see that they two arrays agree on type...
765 if (T1->getElementType() != T2->getElementType())
766 return Error(ErrorMsg,
767 "Appending variables with different element types need to be linked!");
768 if (G1->isConstant() != G2->isConstant())
769 return Error(ErrorMsg,
770 "Appending variables linked with different const'ness!");
771
772 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
773 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
774
Chris Lattnerd490d4f2005-12-06 17:30:58 +0000775 G1->setName(""); // Clear G1's name in case of a conflict!
776
Reid Spencer361e5132004-11-12 20:37:43 +0000777 // Create the new global variable...
778 GlobalVariable *NG =
779 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
780 /*init*/0, First->first, M);
781
782 // Merge the initializer...
783 Inits.reserve(NewSize);
784 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
785 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
786 Inits.push_back(I->getOperand(i));
787 } else {
788 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
789 Constant *CV = Constant::getNullValue(T1->getElementType());
790 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
791 Inits.push_back(CV);
792 }
793 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
794 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
795 Inits.push_back(I->getOperand(i));
796 } else {
797 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
798 Constant *CV = Constant::getNullValue(T2->getElementType());
799 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
800 Inits.push_back(CV);
801 }
802 NG->setInitializer(ConstantArray::get(NewType, Inits));
803 Inits.clear();
804
805 // Replace any uses of the two global variables with uses of the new
806 // global...
807
808 // FIXME: This should rewrite simple/straight-forward uses such as
809 // getelementptr instructions to not use the Cast!
Reid Spencerb341b082006-12-12 05:05:00 +0000810 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
811 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
Reid Spencer361e5132004-11-12 20:37:43 +0000812
813 // Remove the two globals from the module now...
814 M->getGlobalList().erase(G1);
815 M->getGlobalList().erase(G2);
816
817 // Put the new global into the AppendingVars map so that we can handle
818 // linking of more than two vars...
819 Second->second = NG;
820 }
821 AppendingVars.erase(First);
822 }
823
824 return false;
825}
826
827
828// LinkModules - This function links two modules together, with the resulting
829// left module modified to be the composite of the two input modules. If an
830// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
831// the problem. Upon failure, the Dest module could be in a modified state, and
832// shouldn't be relied on to be consistent.
Misha Brukman10468d82005-04-21 22:55:34 +0000833bool
Reid Spencerc4e31532004-12-13 03:00:16 +0000834Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer361e5132004-11-12 20:37:43 +0000835 assert(Dest != 0 && "Invalid Destination module");
836 assert(Src != 0 && "Invalid Source Module");
837
838 if (Dest->getEndianness() == Module::AnyEndianness)
839 Dest->setEndianness(Src->getEndianness());
840 if (Dest->getPointerSize() == Module::AnyPointerSize)
841 Dest->setPointerSize(Src->getPointerSize());
Chris Lattnerb7f59162004-12-10 20:26:15 +0000842 if (Dest->getTargetTriple().empty())
843 Dest->setTargetTriple(Src->getTargetTriple());
Reid Spencer361e5132004-11-12 20:37:43 +0000844
845 if (Src->getEndianness() != Module::AnyEndianness &&
846 Dest->getEndianness() != Src->getEndianness())
Bill Wendlingf3baad32006-12-07 01:30:32 +0000847 cerr << "WARNING: Linking two modules of different endianness!\n";
Reid Spencer361e5132004-11-12 20:37:43 +0000848 if (Src->getPointerSize() != Module::AnyPointerSize &&
849 Dest->getPointerSize() != Src->getPointerSize())
Bill Wendlingf3baad32006-12-07 01:30:32 +0000850 cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattnerb7f59162004-12-10 20:26:15 +0000851 if (!Src->getTargetTriple().empty() &&
852 Dest->getTargetTriple() != Src->getTargetTriple())
Bill Wendlingf3baad32006-12-07 01:30:32 +0000853 cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukman10468d82005-04-21 22:55:34 +0000854
Chris Lattner8ebd2162006-01-24 04:14:29 +0000855 if (!Src->getModuleInlineAsm().empty()) {
856 if (Dest->getModuleInlineAsm().empty())
857 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnerdd2d3fa2006-01-23 23:08:37 +0000858 else
Chris Lattner8ebd2162006-01-24 04:14:29 +0000859 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
860 Src->getModuleInlineAsm());
Chris Lattnerdd2d3fa2006-01-23 23:08:37 +0000861 }
862
Reid Spencer2c4f9a42004-11-25 09:29:44 +0000863 // Update the destination module's dependent libraries list with the libraries
Reid Spencer361e5132004-11-12 20:37:43 +0000864 // from the source module. There's no opportunity for duplicates here as the
865 // Module ensures that duplicate insertions are discarded.
866 Module::lib_iterator SI = Src->lib_begin();
867 Module::lib_iterator SE = Src->lib_end();
868 while ( SI != SE ) {
869 Dest->addLibrary(*SI);
870 ++SI;
871 }
872
873 // LinkTypes - Go through the symbol table of the Src module and see if any
874 // types are named in the src module that are not named in the Dst module.
875 // Make sure there are no type name conflicts.
Reid Spencer361e5132004-11-12 20:37:43 +0000876 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
877
878 // ValueMap - Mapping of values from what they used to be in Src, to what they
879 // are now in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000880 std::map<const Value*, Value*> ValueMap;
881
882 // AppendingVars - Keep track of global variables in the destination module
883 // with appending linkage. After the module is linked together, they are
884 // appended and the module is rewritten.
Reid Spencer361e5132004-11-12 20:37:43 +0000885 std::multimap<std::string, GlobalVariable *> AppendingVars;
886
887 // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
888 // linking by separating globals by type. Until PR411 is fixed, we replicate
889 // it's functionality here.
890 std::map<std::string, GlobalValue*> GlobalsByName;
891
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000892 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
893 I != E; ++I) {
Reid Spencer361e5132004-11-12 20:37:43 +0000894 // Add all of the appending globals already in the Dest module to
895 // AppendingVars.
896 if (I->hasAppendingLinkage())
897 AppendingVars.insert(std::make_pair(I->getName(), I));
898
899 // Keep track of all globals by name.
900 if (!I->hasInternalLinkage() && I->hasName())
901 GlobalsByName[I->getName()] = I;
902 }
903
904 // Keep track of all globals by name.
905 for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
906 if (!I->hasInternalLinkage() && I->hasName())
907 GlobalsByName[I->getName()] = I;
908
909 // Insert all of the globals in src into the Dest module... without linking
910 // initializers (which could refer to functions not yet mapped over).
Reid Spencer361e5132004-11-12 20:37:43 +0000911 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
912 return true;
913
914 // Link the functions together between the two modules, without doing function
915 // bodies... this just adds external function prototypes to the Dest
916 // function... We do this so that when we begin processing function bodies,
917 // all of the global values that may be referenced are available in our
918 // ValueMap.
Reid Spencer361e5132004-11-12 20:37:43 +0000919 if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
920 return true;
921
922 // Update the initializers in the Dest module now that all globals that may
923 // be referenced are in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000924 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
925
926 // Link in the function bodies that are defined in the source module into the
927 // DestModule. This consists basically of copying the function over and
928 // fixing up references to values.
Reid Spencer361e5132004-11-12 20:37:43 +0000929 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
930
931 // If there were any appending global variables, link them together now.
Reid Spencer361e5132004-11-12 20:37:43 +0000932 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
933
934 // If the source library's module id is in the dependent library list of the
935 // destination library, remove it since that module is now linked in.
936 sys::Path modId;
Reid Spencerc9c04732005-07-07 23:21:43 +0000937 modId.set(Src->getModuleIdentifier());
Reid Spencer361e5132004-11-12 20:37:43 +0000938 if (!modId.isEmpty())
939 Dest->removeLibrary(modId.getBasename());
940
941 return false;
942}
943
944// vim: sw=2