blob: 9346c118240e6d358df8650c43a3aa7d2d73fdc2 [file] [log] [blame]
Reid Spencer7f496022004-11-12 20:37:43 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +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 Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
12// Specifically, this:
Chris Lattner8d2de8a2001-10-15 03:12:52 +000013// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000015// * Merges functions between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +000016//
17//===----------------------------------------------------------------------===//
18
Reid Spencer7cc371a2004-11-14 23:27:04 +000019#include "llvm/Linker.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000022#include "llvm/Module.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000023#include "llvm/SymbolTable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000024#include "llvm/Instructions.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000025#include "llvm/Assembly/Writer.h"
Bill Wendling41edad72006-11-27 10:09:12 +000026#include "llvm/Support/Streams.h"
Reid Spencer57a0efa2004-09-11 04:25:17 +000027#include "llvm/System/Path.h"
Bill Wendling1a097e32006-12-07 23:41:45 +000028#include <sstream>
Chris Lattnerf7703df2004-01-09 06:12:26 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner5c377c52001-10-14 23:29:15 +000031// Error - Simple wrapper function to conditionally assign to E and return true.
32// This just makes error return conditions a little bit simpler...
Chris Lattner8166e6e2003-05-13 21:33:43 +000033static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000034 if (E) *E = Message;
35 return true;
36}
37
Reid Spencer719012d2004-11-25 09:29:44 +000038// ToStr - Simple wrapper function to convert a type to a string.
Chris Lattner72cf7df2004-08-21 00:50:59 +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
John Criswell700867b2003-11-04 15:22:26 +000045//
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.
Chris Lattner4c00e532003-05-15 16:30:55 +000062//
Chris Lattnere76c57a2003-08-22 06:07:12 +000063static 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
Chris Lattner4c00e532003-05-15 16:30:55 +000067 // Does the type already exist in the module?
68 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000069 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000071 } 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...
Chris Lattnere76c57a2003-08-22 06:07:12 +000076 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000078 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000079 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000080 }
81 return false;
82}
83
Chris Lattner43f4ba82003-08-22 19:12:55 +000084static const FunctionType *getFT(const PATypeHolder &TH) {
85 return cast<FunctionType>(TH.get());
86}
Chris Lattner9732be72003-08-22 20:16:48 +000087static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000088 return cast<StructType>(TH.get());
89}
Chris Lattnere76c57a2003-08-22 06:07:12 +000090
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.
Chris Lattnere3092c92003-08-23 21:25:54 +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) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000098 const Type *SrcTyT = SrcTy.get();
99 const Type *DestTyT = DestTy.get();
100 if (DestTyT == SrcTyT) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +0000101
Chris Lattnere76c57a2003-08-22 06:07:12 +0000102 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +0000103 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
104 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Misha Brukmanf976c852005-04-21 22:55:34 +0000105
Chris Lattnere76c57a2003-08-22 06:07:12 +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.
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000108 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000109
110 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000111 switch (DestTyT->getTypeID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000112 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000113 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000114 cast<FunctionType>(SrcTyT)->isVarArg() ||
115 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
116 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000117 return true;
118 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000119 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
120 getFT(SrcTy)->getContainedType(i), DestST, "",
121 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000122 return true;
123 return false;
124 }
125 case Type::StructTyID: {
Misha Brukmanf976c852005-04-21 22:55:34 +0000126 if (getST(DestTy)->getNumContainedTypes() !=
Chris Lattner43f4ba82003-08-22 19:12:55 +0000127 getST(SrcTy)->getNumContainedTypes()) return 1;
128 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000129 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
130 getST(SrcTy)->getContainedType(i), DestST, "",
131 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000132 return true;
133 return false;
134 }
135 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000136 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
137 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000138 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000139 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
140 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000141 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000142 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...
Chris Lattnere3092c92003-08-23 21:25:54 +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 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000161 default: assert(0 && "Unexpected type!"); return true;
Misha Brukmanf976c852005-04-21 22:55:34 +0000162 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000163}
164
Chris Lattnere3092c92003-08-23 21:25:54 +0000165static 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
Chris Lattnere76c57a2003-08-22 06:07:12 +0000172
Chris Lattner2c236f32001-11-03 05:18:24 +0000173// 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.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000176static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000177 SymbolTable *DestST = &Dest->getSymbolTable();
178 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000179
180 // Look for a type plane for Type's...
Reid Spencer567bc2c2004-05-25 08:52:20 +0000181 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.
Chris Lattner2c236f32001-11-03 05:18:24 +0000184
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000185 // 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.
Chris Lattner4c00e532003-05-15 16:30:55 +0000188 std::vector<std::string> DelayedTypesToResolve;
189
Reid Spencer567bc2c2004-05-25 08:52:20 +0000190 for ( ; TI != TE; ++TI ) {
191 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000192 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000193
194 // Check to see if this type name is already in the dest module...
Reid Spencer567bc2c2004-05-25 08:52:20 +0000195 Type *Entry = DestST->lookupType(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000196
Chris Lattner4c00e532003-05-15 16:30:55 +0000197 if (ResolveTypes(Entry, RHS, DestST, Name)) {
198 // They look different, save the types 'till later to resolve.
199 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000200 }
201 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000202
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
Chris Lattnere76c57a2003-08-22 06:07:12 +0000208 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000209 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
210 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer567bc2c2004-05-25 08:52:20 +0000211 Type *T1 = SrcST->lookupType(Name);
212 Type *T2 = DestST->lookupType(Name);
Chris Lattner4c00e532003-05-15 16:30:55 +0000213 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) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000222 // Attempt to resolve subelements of types. This allows us to merge these
223 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000224 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
225 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer567bc2c2004-05-25 08:52:20 +0000226 PATypeHolder T1(SrcST->lookupType(Name));
227 PATypeHolder T2(DestST->lookupType(Name));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000228
229 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
230 // We are making progress!
231 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000232
Chris Lattnere76c57a2003-08-22 06:07:12 +0000233 // Go back to the main loop, perhaps we can resolve directly by name
234 // now...
235 break;
236 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000237 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000238
239 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000240 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000241 // Remove the symbol name from the destination.
242 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000243 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000244 }
245 }
246
247
Chris Lattner2c236f32001-11-03 05:18:24 +0000248 return false;
249}
250
Chris Lattner5c2d3352003-01-30 19:53:34 +0000251static void PrintMap(const std::map<const Value*, Value*> &M) {
252 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000253 I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000254 cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000255 I->first->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000256 cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000257 I->second->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000258 cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000259 }
260}
261
262
Chris Lattner0033baf2004-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 Lattner620fd682006-06-01 19:14:22 +0000265// references correctly as well.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000266static Value *RemapOperand(const Value *In,
Chris Lattner0033baf2004-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;
Chris Lattner5c377c52001-10-14 23:29:15 +0000270
Chris Lattner0033baf2004-11-16 17:12:38 +0000271 // Check to see if it's a constant that we are interesting in transforming.
Chris Lattner620fd682006-06-01 19:14:22 +0000272 Value *Result = 0;
Chris Lattner18961502002-06-25 16:12:52 +0000273 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000274 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
275 isa<ConstantAggregateZero>(CPV))
Chris Lattner0033baf2004-11-16 17:12:38 +0000276 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000277
Chris Lattner18961502002-06-25 16:12:52 +0000278 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000279 std::vector<Constant*> Operands(CPA->getNumOperands());
280 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000281 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000282 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000283 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000284 std::vector<Constant*> Operands(CPS->getNumOperands());
285 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000286 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000287 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
Chris Lattnerb976e662004-10-16 18:08:06 +0000288 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000289 Result = const_cast<Constant*>(CPV);
Reid Spencer00dc4792004-07-17 23:50:57 +0000290 } else if (isa<GlobalValue>(CPV)) {
Chris Lattner0033baf2004-11-16 17:12:38 +0000291 Result = cast<Constant>(RemapOperand(CPV, ValueMap));
Chris Lattnera88eb922006-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);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000297 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner27d67212006-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);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000302 } else {
303 assert(0 && "Unknown type of derived type constant value!");
304 }
Chris Lattner620fd682006-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 Lattner0033baf2004-11-16 17:12:38 +0000311 ValueMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000312 return Result;
313 }
Chris Lattner620fd682006-06-01 19:14:22 +0000314
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000315
Bill Wendlinge8156192006-12-07 01:30:32 +0000316 cerr << "LinkModules ValueMap: \n";
Chris Lattner0033baf2004-11-16 17:12:38 +0000317 PrintMap(ValueMap);
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000318
Bill Wendlinge8156192006-12-07 01:30:32 +0000319 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000320 assert(0 && "Couldn't remap value!");
321 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000322}
323
Chris Lattnerc0036282004-08-04 07:05:54 +0000324/// 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
Chris Lattner7b0c84d2004-08-04 07:28:06 +0000341 assert(GV->getName() == Name && ConflictGV->getName() != Name &&
Chris Lattnerc0036282004-08-04 07:05:54 +0000342 "ForceRenaming didn't work");
343}
344
Chris Lattneraee38ea2004-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 Korobeynikovb74ed072006-09-14 18:23:27 +0000362 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000363 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000364 if (Dest->isExternal()) {
365 LinkFromSrc = true;
366 LT = Src->getLinkage();
367 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000368 } else if (Dest->hasExternalWeakLinkage()) {
369 //If the Dest is weak, use the source linkage
370 LinkFromSrc = true;
371 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000372 } else {
373 LinkFromSrc = false;
374 LT = Dest->getLinkage();
375 }
376 } else if (Dest->isExternal() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000377 // If Dest is external but Src is not:
378 LinkFromSrc = true;
379 LT = Src->getLinkage();
380 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
381 if (Src->getLinkage() != Dest->getLinkage())
382 return Error(Err, "Linking globals named '" + Src->getName() +
383 "': can only link appending global with another appending global!");
384 LinkFromSrc = true; // Special cased.
385 LT = Src->getLinkage();
386 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000387 // At this point we know that Dest has LinkOnce, External*, Weak, DLL* linkage.
388 if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
389 Dest->hasExternalWeakLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000390 LinkFromSrc = true;
391 LT = Src->getLinkage();
392 } else {
393 LinkFromSrc = false;
394 LT = Dest->getLinkage();
395 }
396 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000397 // At this point we know that Src has External* or DLL* linkage.
398 if (Src->hasExternalWeakLinkage()) {
399 LinkFromSrc = false;
400 LT = Dest->getLinkage();
401 } else {
402 LinkFromSrc = true;
403 LT = GlobalValue::ExternalLinkage;
404 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000405 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000406 assert((Dest->hasExternalLinkage() ||
407 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000408 Dest->hasDLLExportLinkage() ||
409 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000410 (Src->hasExternalLinkage() ||
411 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000412 Src->hasDLLExportLinkage() ||
413 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000414 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000415 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000416 "': symbol multiply defined!");
417 }
418 return false;
419}
Chris Lattner5c377c52001-10-14 23:29:15 +0000420
421// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000422// them into the dest module.
Chris Lattneraee38ea2004-12-03 22:18:41 +0000423static bool LinkGlobals(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000424 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000425 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5a837de2004-08-04 07:44:58 +0000426 std::map<std::string, GlobalValue*> &GlobalsByName,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000427 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000428 // We will need a module level symbol table if the src module has a module
429 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000430 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukmanf976c852005-04-21 22:55:34 +0000431
Chris Lattner5c377c52001-10-14 23:29:15 +0000432 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000433 for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
434 I != E; ++I) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000435 GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000436 GlobalVariable *DGV = 0;
Chris Lattner5a837de2004-08-04 07:44:58 +0000437 // Check to see if may have to link the global.
Chris Lattneraad2deb2004-08-04 22:39:54 +0000438 if (SGV->hasName() && !SGV->hasInternalLinkage())
439 if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
440 SGV->getType()->getElementType()))) {
441 std::map<std::string, GlobalValue*>::iterator EGV =
442 GlobalsByName.find(SGV->getName());
443 if (EGV != GlobalsByName.end())
444 DGV = dyn_cast<GlobalVariable>(EGV->second);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000445 if (DGV)
446 // If types don't agree due to opaque types, try to resolve them.
447 RecursiveResolveTypes(SGV->getType(), DGV->getType(),ST, "");
Chris Lattneraad2deb2004-08-04 22:39:54 +0000448 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000449
Chris Lattneraee38ea2004-12-03 22:18:41 +0000450 if (DGV && DGV->hasInternalLinkage())
451 DGV = 0;
452
Andrew Lenharth8753c442006-12-15 17:35:32 +0000453 assert(SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000454 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage() &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000455 "Global must either be external or have an initializer!");
456
Chris Lattnerb324bd72006-11-09 05:18:12 +0000457 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
458 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000459 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
460 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000461
Chris Lattneraee38ea2004-12-03 22:18:41 +0000462 if (!DGV) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000463 // No linking to be performed, simply create an identical version of the
464 // symbol over in the dest module... the initializer will be filled in
465 // later by LinkGlobalInits...
Chris Lattner2719bac2003-04-21 21:15:04 +0000466 GlobalVariable *NewDGV =
467 new GlobalVariable(SGV->getType()->getElementType(),
468 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
469 SGV->getName(), Dest);
Chris Lattner11273152006-06-16 01:24:04 +0000470 // Propagate alignment info.
471 NewDGV->setAlignment(SGV->getAlignment());
472
Chris Lattner2719bac2003-04-21 21:15:04 +0000473 // If the LLVM runtime renamed the global, but it is an externally visible
474 // symbol, DGV must be an existing global with internal linkage. Rename
475 // it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000476 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
477 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000478
479 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000480 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000481 if (SGV->hasAppendingLinkage())
482 // Keep track that this is an appending variable...
483 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattneraee38ea2004-12-03 22:18:41 +0000484 } else if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000485 // No linking is performed yet. Just insert a new copy of the global, and
486 // keep track of the fact that it is an appending variable in the
487 // AppendingVars map. The name is cleared out so that no linkage is
488 // performed.
489 GlobalVariable *NewDGV =
490 new GlobalVariable(SGV->getType()->getElementType(),
491 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
492 "", Dest);
493
Chris Lattner11273152006-06-16 01:24:04 +0000494 // Propagate alignment info.
495 NewDGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
496
Chris Lattner8166e6e2003-05-13 21:33:43 +0000497 // Make sure to remember this mapping...
498 ValueMap.insert(std::make_pair(SGV, NewDGV));
499
500 // Keep track that this is an appending variable...
501 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000502 } else {
Chris Lattner11273152006-06-16 01:24:04 +0000503 // Propagate alignment info.
504 DGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
505
Chris Lattneraee38ea2004-12-03 22:18:41 +0000506 // Otherwise, perform the mapping as instructed by GetLinkageResult. If
507 // the types don't match, and if we are to link from the source, nuke DGV
508 // and create a new one of the appropriate type.
509 if (SGV->getType() != DGV->getType() && LinkFromSrc) {
510 GlobalVariable *NewDGV =
511 new GlobalVariable(SGV->getType()->getElementType(),
512 DGV->isConstant(), DGV->getLinkage());
Chris Lattner11273152006-06-16 01:24:04 +0000513 NewDGV->setAlignment(DGV->getAlignment());
Chris Lattneraee38ea2004-12-03 22:18:41 +0000514 Dest->getGlobalList().insert(DGV, NewDGV);
Reid Spencer4da49122006-12-12 05:05:00 +0000515 DGV->replaceAllUsesWith(
516 ConstantExpr::getBitCast(NewDGV, DGV->getType()));
Chris Lattneraee38ea2004-12-03 22:18:41 +0000517 DGV->eraseFromParent();
518 NewDGV->setName(SGV->getName());
519 DGV = NewDGV;
520 }
521
522 DGV->setLinkage(NewLinkage);
523
524 if (LinkFromSrc) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000525 // Inherit const as appropriate
Chris Lattnere6f8c5a2005-02-12 19:20:28 +0000526 DGV->setConstant(SGV->isConstant());
Chris Lattneraee38ea2004-12-03 22:18:41 +0000527 DGV->setInitializer(0);
528 } else {
529 if (SGV->isConstant() && !DGV->isConstant()) {
Chris Lattnere6f8c5a2005-02-12 19:20:28 +0000530 if (DGV->isExternal())
Chris Lattneraee38ea2004-12-03 22:18:41 +0000531 DGV->setConstant(true);
532 }
Chris Lattnerc8ef1ed2004-12-04 18:54:48 +0000533 SGV->setLinkage(GlobalValue::ExternalLinkage);
534 SGV->setInitializer(0);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000535 }
536
Reid Spencer4da49122006-12-12 05:05:00 +0000537 ValueMap.insert(
538 std::make_pair(SGV, ConstantExpr::getBitCast(DGV, SGV->getType())));
Chris Lattner5c377c52001-10-14 23:29:15 +0000539 }
540 }
541 return false;
542}
543
544
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000545// LinkGlobalInits - Update the initializers in the Dest module now that all
546// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000547static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000548 std::map<const Value*, Value*> &ValueMap,
549 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000550
551 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000552 for (Module::const_global_iterator I = Src->global_begin(),
553 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000554 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000555
556 if (SGV->hasInitializer()) { // Only process initialized GV's
557 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000558 Constant *SInit =
Chris Lattner0033baf2004-11-16 17:12:38 +0000559 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000560
Misha Brukmanf976c852005-04-21 22:55:34 +0000561 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000562 if (DGV->hasInitializer()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000563 if (SGV->hasExternalLinkage()) {
564 if (DGV->getInitializer() != SInit)
Misha Brukmanf976c852005-04-21 22:55:34 +0000565 return Error(Err, "Global Variable Collision on '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000566 ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
Chris Lattner4ad02e72003-04-16 20:28:45 +0000567 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000568 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000569 // Nothing is required, mapped values will take the new global
570 // automatically.
Chris Lattner57cb9882004-02-17 21:56:04 +0000571 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
572 // Nothing is required, mapped values will take the new global
573 // automatically.
Chris Lattner4ad02e72003-04-16 20:28:45 +0000574 } else if (DGV->hasAppendingLinkage()) {
575 assert(0 && "Appending linkage unimplemented!");
576 } else {
577 assert(0 && "Unknown linkage!");
578 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000579 } else {
580 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000581 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000582 }
583 }
584 }
585 return false;
586}
Chris Lattner5c377c52001-10-14 23:29:15 +0000587
Chris Lattner79df7c02002-03-26 18:01:55 +0000588// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000589// without doing function bodies... this just adds external function prototypes
590// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000591//
Chris Lattner79df7c02002-03-26 18:01:55 +0000592static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000593 std::map<const Value*, Value*> &ValueMap,
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000594 std::map<std::string, GlobalValue*> &GlobalsByName,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000595 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000596 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukmanf976c852005-04-21 22:55:34 +0000597
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000598 // Loop over all of the functions in the src module, mapping them over as we
599 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000600 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000601 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000602 Function *DF = 0;
Chris Lattner5a837de2004-08-04 07:44:58 +0000603 if (SF->hasName() && !SF->hasInternalLinkage()) {
604 // Check to see if may have to link the function.
Chris Lattneraad2deb2004-08-04 22:39:54 +0000605 if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
606 std::map<std::string, GlobalValue*>::iterator EF =
607 GlobalsByName.find(SF->getName());
608 if (EF != GlobalsByName.end())
609 DF = dyn_cast<Function>(EF->second);
610 if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
611 DF = 0; // FIXME: gross.
612 }
Chris Lattner5a837de2004-08-04 07:44:58 +0000613 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000614
Chris Lattner4ad02e72003-04-16 20:28:45 +0000615 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000616 // Function does not already exist, simply insert an function signature
617 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000618 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
619 SF->getName(), Dest);
Chris Lattnercb9048a2005-05-09 01:09:39 +0000620 NewDF->setCallingConv(SF->getCallingConv());
Chris Lattner2719bac2003-04-21 21:15:04 +0000621
622 // If the LLVM runtime renamed the function, but it is an externally
623 // visible symbol, DF must be an existing function with internal linkage.
624 // Rename it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000625 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
Chris Lattner82b5b212004-08-04 22:29:05 +0000626 ForceRenaming(NewDF, SF->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000627
628 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000629 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000630 } else if (SF->isExternal()) {
631 // If SF is external or if both SF & DF are external.. Just link the
632 // external functions, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000633 if (SF->hasDLLImportLinkage()) {
634 if (DF->isExternal()) {
635 ValueMap.insert(std::make_pair(SF, DF));
636 DF->setLinkage(SF->getLinkage());
637 }
638 } else {
639 ValueMap.insert(std::make_pair(SF, DF));
640 }
641 } else if (DF->isExternal() && !DF->hasDLLImportLinkage()) {
642 // If DF is external but SF is not...
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000643 // Link the external functions, update linkage qualifiers
644 ValueMap.insert(std::make_pair(SF, DF));
645 DF->setLinkage(SF->getLinkage());
Chris Lattner35956552003-10-27 16:39:39 +0000646 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000647 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
Chris Lattner72ac148d2003-10-16 18:29:00 +0000648 ValueMap.insert(std::make_pair(SF, DF));
649
Chris Lattner35956552003-10-27 16:39:39 +0000650 // Linkonce+Weak = Weak
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000651 // *+External Weak = *
652 if ((DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) ||
653 DF->hasExternalWeakLinkage())
Chris Lattner35956552003-10-27 16:39:39 +0000654 DF->setLinkage(SF->getLinkage());
655
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000656
Chris Lattner35956552003-10-27 16:39:39 +0000657 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000658 // At this point we know that SF has LinkOnce or External* linkage.
Chris Lattner72ac148d2003-10-16 18:29:00 +0000659 ValueMap.insert(std::make_pair(SF, DF));
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000660 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage())
661 // Don't inherit linkonce & external weak linkage
Chris Lattner72ac148d2003-10-16 18:29:00 +0000662 DF->setLinkage(SF->getLinkage());
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000663 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000664 return Error(Err, "Functions named '" + SF->getName() +
665 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000666 } else if (SF->hasExternalLinkage()) {
667 // The function is defined in both modules!!
Misha Brukmanf976c852005-04-21 22:55:34 +0000668 return Error(Err, "Function '" +
669 ToStr(SF->getFunctionType(), Src) + "':\"" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000670 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000671 } else {
672 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000673 }
674 }
675 return false;
676}
677
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000678// LinkFunctionBody - Copy the source function over into the dest function and
679// fix up references to values. At this point we know that Dest is an external
680// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000681static bool LinkFunctionBody(Function *Dest, Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000682 std::map<const Value*, Value*> &GlobalMap,
683 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000684 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c377c52001-10-14 23:29:15 +0000685
Chris Lattner0033baf2004-11-16 17:12:38 +0000686 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +0000687 Function::arg_iterator DI = Dest->arg_begin();
688 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000689 I != E; ++I, ++DI) {
690 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000691
692 // Add a mapping to our local map
Chris Lattner0033baf2004-11-16 17:12:38 +0000693 GlobalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000694 }
695
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000696 // Splice the body of the source function into the dest function.
697 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +0000698
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000699 // At this point, all of the instructions and values of the function are now
700 // copied over. The only problem is that they are still referencing values in
701 // the Source function as operands. Loop through all of the operands of the
702 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000703 //
Chris Lattner18961502002-06-25 16:12:52 +0000704 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
705 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
706 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000707 OI != OE; ++OI)
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000708 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner0033baf2004-11-16 17:12:38 +0000709 *OI = RemapOperand(*OI, GlobalMap);
710
711 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000712 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
713 I != E; ++I)
Chris Lattner0033baf2004-11-16 17:12:38 +0000714 GlobalMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +0000715
716 return false;
717}
718
719
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000720// LinkFunctionBodies - Link in the function bodies that are defined in the
721// source module into the DestModule. This consists basically of copying the
722// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000723static bool LinkFunctionBodies(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000724 std::map<const Value*, Value*> &ValueMap,
725 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000726
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000727 // Loop over all of the functions in the src module, mapping them over as we
728 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000729 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Chris Lattner18961502002-06-25 16:12:52 +0000730 if (!SF->isExternal()) { // No body if function is external
731 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000732
Chris Lattner18961502002-06-25 16:12:52 +0000733 // DF not external SF external?
Chris Lattner35956552003-10-27 16:39:39 +0000734 if (DF->isExternal()) {
735 // Only provide the function body if there isn't one already.
736 if (LinkFunctionBody(DF, SF, ValueMap, Err))
737 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000738 }
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000739 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000740 }
741 return false;
742}
743
Chris Lattner8166e6e2003-05-13 21:33:43 +0000744// LinkAppendingVars - If there were any appending global variables, link them
745// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000746static bool LinkAppendingVars(Module *M,
747 std::multimap<std::string, GlobalVariable *> &AppendingVars,
748 std::string *ErrorMsg) {
749 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +0000750
Chris Lattner8166e6e2003-05-13 21:33:43 +0000751 // Loop over the multimap of appending vars, processing any variables with the
752 // same name, forming a new appending global variable with both of the
753 // initializers merged together, then rewrite references to the old variables
754 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000755 std::vector<Constant*> Inits;
756 while (AppendingVars.size() > 1) {
757 // Get the first two elements in the map...
758 std::multimap<std::string,
759 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
760
761 // If the first two elements are for different names, there is no pair...
762 // Otherwise there is a pair, so link them together...
763 if (First->first == Second->first) {
764 GlobalVariable *G1 = First->second, *G2 = Second->second;
765 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
766 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +0000767
Chris Lattner8166e6e2003-05-13 21:33:43 +0000768 // Check to see that they two arrays agree on type...
769 if (T1->getElementType() != T2->getElementType())
770 return Error(ErrorMsg,
771 "Appending variables with different element types need to be linked!");
772 if (G1->isConstant() != G2->isConstant())
773 return Error(ErrorMsg,
774 "Appending variables linked with different const'ness!");
775
776 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
777 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
778
Chris Lattnered74a4e2005-12-06 17:30:58 +0000779 G1->setName(""); // Clear G1's name in case of a conflict!
780
Chris Lattner8166e6e2003-05-13 21:33:43 +0000781 // Create the new global variable...
782 GlobalVariable *NG =
783 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
784 /*init*/0, First->first, M);
785
786 // Merge the initializer...
787 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +0000788 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
789 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000790 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +0000791 } else {
792 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
793 Constant *CV = Constant::getNullValue(T1->getElementType());
794 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
795 Inits.push_back(CV);
796 }
797 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
798 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000799 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +0000800 } else {
801 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
802 Constant *CV = Constant::getNullValue(T2->getElementType());
803 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
804 Inits.push_back(CV);
805 }
Chris Lattner8166e6e2003-05-13 21:33:43 +0000806 NG->setInitializer(ConstantArray::get(NewType, Inits));
807 Inits.clear();
808
809 // Replace any uses of the two global variables with uses of the new
810 // global...
811
812 // FIXME: This should rewrite simple/straight-forward uses such as
813 // getelementptr instructions to not use the Cast!
Reid Spencer4da49122006-12-12 05:05:00 +0000814 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
815 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000816
817 // Remove the two globals from the module now...
818 M->getGlobalList().erase(G1);
819 M->getGlobalList().erase(G2);
820
821 // Put the new global into the AppendingVars map so that we can handle
822 // linking of more than two vars...
823 Second->second = NG;
824 }
825 AppendingVars.erase(First);
826 }
827
828 return false;
829}
Chris Lattner52f7e902001-10-13 07:03:50 +0000830
831
832// LinkModules - This function links two modules together, with the resulting
833// left module modified to be the composite of the two input modules. If an
834// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000835// the problem. Upon failure, the Dest module could be in a modified state, and
836// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +0000837bool
Reid Spencer0ba9e212004-12-13 03:00:16 +0000838Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +0000839 assert(Dest != 0 && "Invalid Destination module");
840 assert(Src != 0 && "Invalid Source Module");
841
Chris Lattner873c5e72003-08-24 19:26:42 +0000842 if (Dest->getEndianness() == Module::AnyEndianness)
843 Dest->setEndianness(Src->getEndianness());
844 if (Dest->getPointerSize() == Module::AnyPointerSize)
845 Dest->setPointerSize(Src->getPointerSize());
Chris Lattner152f19a2004-12-10 20:26:15 +0000846 if (Dest->getTargetTriple().empty())
847 Dest->setTargetTriple(Src->getTargetTriple());
Chris Lattner873c5e72003-08-24 19:26:42 +0000848
849 if (Src->getEndianness() != Module::AnyEndianness &&
850 Dest->getEndianness() != Src->getEndianness())
Bill Wendlinge8156192006-12-07 01:30:32 +0000851 cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000852 if (Src->getPointerSize() != Module::AnyPointerSize &&
853 Dest->getPointerSize() != Src->getPointerSize())
Bill Wendlinge8156192006-12-07 01:30:32 +0000854 cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +0000855 if (!Src->getTargetTriple().empty() &&
856 Dest->getTargetTriple() != Src->getTargetTriple())
Bill Wendlinge8156192006-12-07 01:30:32 +0000857 cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukmanf976c852005-04-21 22:55:34 +0000858
Chris Lattner66316012006-01-24 04:14:29 +0000859 if (!Src->getModuleInlineAsm().empty()) {
860 if (Dest->getModuleInlineAsm().empty())
861 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +0000862 else
Chris Lattner66316012006-01-24 04:14:29 +0000863 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
864 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +0000865 }
866
Reid Spencer719012d2004-11-25 09:29:44 +0000867 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +0000868 // from the source module. There's no opportunity for duplicates here as the
869 // Module ensures that duplicate insertions are discarded.
870 Module::lib_iterator SI = Src->lib_begin();
871 Module::lib_iterator SE = Src->lib_end();
872 while ( SI != SE ) {
873 Dest->addLibrary(*SI);
874 ++SI;
875 }
876
Chris Lattner2c236f32001-11-03 05:18:24 +0000877 // LinkTypes - Go through the symbol table of the Src module and see if any
878 // types are named in the src module that are not named in the Dst module.
879 // Make sure there are no type name conflicts.
Chris Lattner2c236f32001-11-03 05:18:24 +0000880 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
881
Chris Lattner5c377c52001-10-14 23:29:15 +0000882 // ValueMap - Mapping of values from what they used to be in Src, to what they
883 // are now in Dest.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000884 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000885
Chris Lattner8166e6e2003-05-13 21:33:43 +0000886 // AppendingVars - Keep track of global variables in the destination module
887 // with appending linkage. After the module is linked together, they are
888 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000889 std::multimap<std::string, GlobalVariable *> AppendingVars;
890
Chris Lattner5a837de2004-08-04 07:44:58 +0000891 // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
892 // linking by separating globals by type. Until PR411 is fixed, we replicate
893 // it's functionality here.
894 std::map<std::string, GlobalValue*> GlobalsByName;
895
Chris Lattner11273152006-06-16 01:24:04 +0000896 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
897 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +0000898 // Add all of the appending globals already in the Dest module to
899 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +0000900 if (I->hasAppendingLinkage())
901 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000902
Chris Lattner5a837de2004-08-04 07:44:58 +0000903 // Keep track of all globals by name.
904 if (!I->hasInternalLinkage() && I->hasName())
905 GlobalsByName[I->getName()] = I;
906 }
907
908 // Keep track of all globals by name.
909 for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
910 if (!I->hasInternalLinkage() && I->hasName())
911 GlobalsByName[I->getName()] = I;
912
Chris Lattner8166e6e2003-05-13 21:33:43 +0000913 // Insert all of the globals in src into the Dest module... without linking
914 // initializers (which could refer to functions not yet mapped over).
Chris Lattner5a837de2004-08-04 07:44:58 +0000915 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
916 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000917
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000918 // Link the functions together between the two modules, without doing function
919 // bodies... this just adds external function prototypes to the Dest
920 // function... We do this so that when we begin processing function bodies,
921 // all of the global values that may be referenced are available in our
922 // ValueMap.
Chris Lattner5a837de2004-08-04 07:44:58 +0000923 if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
924 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000925
Chris Lattner6cdf1972002-07-18 00:13:08 +0000926 // Update the initializers in the Dest module now that all globals that may
927 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +0000928 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
929
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000930 // Link in the function bodies that are defined in the source module into the
931 // DestModule. This consists basically of copying the function over and
932 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +0000933 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000934
Chris Lattner8166e6e2003-05-13 21:33:43 +0000935 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000936 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
937
Reid Spencer57a0efa2004-09-11 04:25:17 +0000938 // If the source library's module id is in the dependent library list of the
939 // destination library, remove it since that module is now linked in.
940 sys::Path modId;
Reid Spencerdd04df02005-07-07 23:21:43 +0000941 modId.set(Src->getModuleIdentifier());
Reid Spencer07adb282004-11-05 22:15:36 +0000942 if (!modId.isEmpty())
943 Dest->removeLibrary(modId.getBasename());
Reid Spencer57a0efa2004-09-11 04:25:17 +0000944
Chris Lattner52f7e902001-10-13 07:03:50 +0000945 return false;
946}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000947
Reid Spencer567bc2c2004-05-25 08:52:20 +0000948// vim: sw=2