blob: 753ebcc955ffb9ba82269acb3ecf47eaaeb45c3d [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"
Reid Spencer78d033e2007-01-06 07:24:44 +000024#include "llvm/TypeSymbolTable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000025#include "llvm/Instructions.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000026#include "llvm/Assembly/Writer.h"
Bill Wendling41edad72006-11-27 10:09:12 +000027#include "llvm/Support/Streams.h"
Reid Spencer57a0efa2004-09-11 04:25:17 +000028#include "llvm/System/Path.h"
Bill Wendling1a097e32006-12-07 23:41:45 +000029#include <sstream>
Chris Lattnerf7703df2004-01-09 06:12:26 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattner5c377c52001-10-14 23:29:15 +000032// Error - Simple wrapper function to conditionally assign to E and return true.
33// This just makes error return conditions a little bit simpler...
Chris Lattner8166e6e2003-05-13 21:33:43 +000034static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000035 if (E) *E = Message;
36 return true;
37}
38
Reid Spencer719012d2004-11-25 09:29:44 +000039// ToStr - Simple wrapper function to convert a type to a string.
Chris Lattner72cf7df2004-08-21 00:50:59 +000040static std::string ToStr(const Type *Ty, const Module *M) {
41 std::ostringstream OS;
42 WriteTypeSymbolic(OS, Ty, M);
43 return OS.str();
44}
45
John Criswell700867b2003-11-04 15:22:26 +000046//
47// Function: ResolveTypes()
48//
49// Description:
50// Attempt to link the two specified types together.
51//
52// Inputs:
53// DestTy - The type to which we wish to resolve.
54// SrcTy - The original type which we want to resolve.
55// Name - The name of the type.
56//
57// Outputs:
58// DestST - The symbol table in which the new type should be placed.
59//
60// Return value:
61// true - There is an error and the types cannot yet be linked.
62// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000063//
Chris Lattnere76c57a2003-08-22 06:07:12 +000064static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
Reid Spencer78d033e2007-01-06 07:24:44 +000065 TypeSymbolTable *DestST, const std::string &Name) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000066 if (DestTy == SrcTy) return false; // If already equal, noop
67
Chris Lattner4c00e532003-05-15 16:30:55 +000068 // Does the type already exist in the module?
69 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000070 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
71 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000072 } else {
73 return true; // Cannot link types... neither is opaque and not-equal
74 }
75 } else { // Type not in dest module. Add it now.
76 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000077 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
78 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000079 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000080 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000081 }
82 return false;
83}
84
Chris Lattner43f4ba82003-08-22 19:12:55 +000085static const FunctionType *getFT(const PATypeHolder &TH) {
86 return cast<FunctionType>(TH.get());
87}
Chris Lattner9732be72003-08-22 20:16:48 +000088static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000089 return cast<StructType>(TH.get());
90}
Chris Lattnere76c57a2003-08-22 06:07:12 +000091
92// RecursiveResolveTypes - This is just like ResolveTypes, except that it
93// recurses down into derived types, merging the used types if the parent types
94// are compatible.
Chris Lattnere3092c92003-08-23 21:25:54 +000095static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
96 const PATypeHolder &SrcTy,
Reid Spencer78d033e2007-01-06 07:24:44 +000097 TypeSymbolTable *DestST,
98 const std::string &Name,
Chris Lattnere3092c92003-08-23 21:25:54 +000099 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000100 const Type *SrcTyT = SrcTy.get();
101 const Type *DestTyT = DestTy.get();
102 if (DestTyT == SrcTyT) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +0000103
Chris Lattnere76c57a2003-08-22 06:07:12 +0000104 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +0000105 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
106 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Misha Brukmanf976c852005-04-21 22:55:34 +0000107
Chris Lattnere76c57a2003-08-22 06:07:12 +0000108 // Two types cannot be resolved together if they are of different primitive
109 // type. For example, we cannot resolve an int to a float.
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000110 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000111
112 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000113 switch (DestTyT->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000114 case Type::IntegerTyID: {
115 if (cast<IntegerType>(DestTyT)->getBitWidth() !=
116 cast<IntegerType>(SrcTyT)->getBitWidth())
117 return true;
118 return false;
119 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000120 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000121 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000122 cast<FunctionType>(SrcTyT)->isVarArg() ||
123 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
124 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000125 return true;
126 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000127 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
128 getFT(SrcTy)->getContainedType(i), DestST, "",
129 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000130 return true;
131 return false;
132 }
133 case Type::StructTyID: {
Misha Brukmanf976c852005-04-21 22:55:34 +0000134 if (getST(DestTy)->getNumContainedTypes() !=
Chris Lattner43f4ba82003-08-22 19:12:55 +0000135 getST(SrcTy)->getNumContainedTypes()) return 1;
136 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000137 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
138 getST(SrcTy)->getContainedType(i), DestST, "",
139 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000140 return true;
141 return false;
142 }
143 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000144 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
145 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000146 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000147 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
148 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000149 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000150 case Type::PointerTyID: {
151 // If this is a pointer type, check to see if we have already seen it. If
152 // so, we are in a recursive branch. Cut off the search now. We cannot use
153 // an associative container for this search, because the type pointers (keys
154 // in the container) change whenever types get resolved...
Chris Lattnere3092c92003-08-23 21:25:54 +0000155 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
156 if (Pointers[i].first == DestTy)
157 return Pointers[i].second != SrcTy;
158
159 // Otherwise, add the current pointers to the vector to stop recursion on
160 // this pair.
161 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
162 bool Result =
163 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
164 cast<PointerType>(SrcTy.get())->getElementType(),
165 DestST, "", Pointers);
166 Pointers.pop_back();
167 return Result;
168 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000169 default: assert(0 && "Unexpected type!"); return true;
Misha Brukmanf976c852005-04-21 22:55:34 +0000170 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000171}
172
Chris Lattnere3092c92003-08-23 21:25:54 +0000173static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
174 const PATypeHolder &SrcTy,
Reid Spencer78d033e2007-01-06 07:24:44 +0000175 TypeSymbolTable *DestST,
176 const std::string &Name){
Chris Lattnere3092c92003-08-23 21:25:54 +0000177 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
178 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
179}
180
Chris Lattnere76c57a2003-08-22 06:07:12 +0000181
Chris Lattner2c236f32001-11-03 05:18:24 +0000182// LinkTypes - Go through the symbol table of the Src module and see if any
183// types are named in the src module that are not named in the Dst module.
184// Make sure there are no type name conflicts.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000185static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000186 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
187 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000188
189 // Look for a type plane for Type's...
Reid Spencer78d033e2007-01-06 07:24:44 +0000190 TypeSymbolTable::const_iterator TI = SrcST->begin();
191 TypeSymbolTable::const_iterator TE = SrcST->end();
Reid Spencer567bc2c2004-05-25 08:52:20 +0000192 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000193
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000194 // Some types cannot be resolved immediately because they depend on other
195 // types being resolved to each other first. This contains a list of types we
196 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000197 std::vector<std::string> DelayedTypesToResolve;
198
Reid Spencer567bc2c2004-05-25 08:52:20 +0000199 for ( ; TI != TE; ++TI ) {
200 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000201 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000202
203 // Check to see if this type name is already in the dest module...
Reid Spencer78d033e2007-01-06 07:24:44 +0000204 Type *Entry = DestST->lookup(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000205
Chris Lattner4c00e532003-05-15 16:30:55 +0000206 if (ResolveTypes(Entry, RHS, DestST, Name)) {
207 // They look different, save the types 'till later to resolve.
208 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000209 }
210 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000211
212 // Iteratively resolve types while we can...
213 while (!DelayedTypesToResolve.empty()) {
214 // Loop over all of the types, attempting to resolve them if possible...
215 unsigned OldSize = DelayedTypesToResolve.size();
216
Chris Lattnere76c57a2003-08-22 06:07:12 +0000217 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000218 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
219 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000220 Type *T1 = SrcST->lookup(Name);
221 Type *T2 = DestST->lookup(Name);
Chris Lattner4c00e532003-05-15 16:30:55 +0000222 if (!ResolveTypes(T2, T1, DestST, Name)) {
223 // We are making progress!
224 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
225 --i;
226 }
227 }
228
229 // Did we not eliminate any types?
230 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000231 // Attempt to resolve subelements of types. This allows us to merge these
232 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000233 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
234 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000235 PATypeHolder T1(SrcST->lookup(Name));
236 PATypeHolder T2(DestST->lookup(Name));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000237
238 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
239 // We are making progress!
240 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000241
Chris Lattnere76c57a2003-08-22 06:07:12 +0000242 // Go back to the main loop, perhaps we can resolve directly by name
243 // now...
244 break;
245 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000246 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000247
248 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000249 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000250 // Remove the symbol name from the destination.
251 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000252 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000253 }
254 }
255
256
Chris Lattner2c236f32001-11-03 05:18:24 +0000257 return false;
258}
259
Chris Lattner5c2d3352003-01-30 19:53:34 +0000260static void PrintMap(const std::map<const Value*, Value*> &M) {
261 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000262 I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000263 cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000264 I->first->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000265 cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000266 I->second->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000267 cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000268 }
269}
270
271
Chris Lattner0033baf2004-11-16 17:12:38 +0000272// RemapOperand - Use ValueMap to convert references from one module to another.
273// This is somewhat sophisticated in that it can automatically handle constant
Chris Lattner620fd682006-06-01 19:14:22 +0000274// references correctly as well.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000275static Value *RemapOperand(const Value *In,
Chris Lattner0033baf2004-11-16 17:12:38 +0000276 std::map<const Value*, Value*> &ValueMap) {
277 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
278 if (I != ValueMap.end()) return I->second;
Chris Lattner5c377c52001-10-14 23:29:15 +0000279
Chris Lattner0033baf2004-11-16 17:12:38 +0000280 // Check to see if it's a constant that we are interesting in transforming.
Chris Lattner620fd682006-06-01 19:14:22 +0000281 Value *Result = 0;
Chris Lattner18961502002-06-25 16:12:52 +0000282 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000283 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000284 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
Chris Lattner0033baf2004-11-16 17:12:38 +0000285 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000286
Chris Lattner18961502002-06-25 16:12:52 +0000287 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000288 std::vector<Constant*> Operands(CPA->getNumOperands());
289 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000290 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000291 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000292 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000293 std::vector<Constant*> Operands(CPS->getNumOperands());
294 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000295 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000296 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
Chris Lattnerb976e662004-10-16 18:08:06 +0000297 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000298 Result = const_cast<Constant*>(CPV);
Reid Spencer00dc4792004-07-17 23:50:57 +0000299 } else if (isa<GlobalValue>(CPV)) {
Chris Lattner0033baf2004-11-16 17:12:38 +0000300 Result = cast<Constant>(RemapOperand(CPV, ValueMap));
Chris Lattnera88eb922006-01-19 23:15:58 +0000301 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CPV)) {
302 std::vector<Constant*> Operands(CP->getNumOperands());
303 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
304 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
305 Result = ConstantPacked::get(Operands);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000306 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner27d67212006-07-14 22:21:31 +0000307 std::vector<Constant*> Ops;
308 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
309 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
310 Result = CE->getWithOperands(Ops);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000311 } else {
312 assert(0 && "Unknown type of derived type constant value!");
313 }
Chris Lattner620fd682006-06-01 19:14:22 +0000314 } else if (isa<InlineAsm>(In)) {
315 Result = const_cast<Value*>(In);
316 }
317
318 // Cache the mapping in our local map structure...
319 if (Result) {
Chris Lattner0033baf2004-11-16 17:12:38 +0000320 ValueMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000321 return Result;
322 }
Chris Lattner620fd682006-06-01 19:14:22 +0000323
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000324
Bill Wendlinge8156192006-12-07 01:30:32 +0000325 cerr << "LinkModules ValueMap: \n";
Chris Lattner0033baf2004-11-16 17:12:38 +0000326 PrintMap(ValueMap);
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000327
Bill Wendlinge8156192006-12-07 01:30:32 +0000328 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000329 assert(0 && "Couldn't remap value!");
330 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000331}
332
Chris Lattnerc0036282004-08-04 07:05:54 +0000333/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
334/// in the symbol table. This is good for all clients except for us. Go
335/// through the trouble to force this back.
336static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
337 assert(GV->getName() != Name && "Can't force rename to self");
Reid Spencer78d033e2007-01-06 07:24:44 +0000338 SymbolTable &ST = GV->getParent()->getValueSymbolTable();
Chris Lattnerc0036282004-08-04 07:05:54 +0000339
340 // If there is a conflict, rename the conflict.
341 Value *ConflictVal = ST.lookup(GV->getType(), Name);
342 assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
343 GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
344 assert(ConflictGV->hasInternalLinkage() &&
345 "Not conflicting with a static global, should link instead!");
346
347 ConflictGV->setName(""); // Eliminate the conflict
348 GV->setName(Name); // Force the name back
349 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner7b0c84d2004-08-04 07:28:06 +0000350 assert(GV->getName() == Name && ConflictGV->getName() != Name &&
Chris Lattnerc0036282004-08-04 07:05:54 +0000351 "ForceRenaming didn't work");
352}
353
Chris Lattneraee38ea2004-12-03 22:18:41 +0000354/// GetLinkageResult - This analyzes the two global values and determines what
355/// the result will look like in the destination module. In particular, it
356/// computes the resultant linkage type, computes whether the global in the
357/// source should be copied over to the destination (replacing the existing
358/// one), and computes whether this linkage is an error or not.
359static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
360 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
361 std::string *Err) {
362 assert((!Dest || !Src->hasInternalLinkage()) &&
363 "If Src has internal linkage, Dest shouldn't be set!");
364 if (!Dest) {
365 // Linking something to nothing.
366 LinkFromSrc = true;
367 LT = Src->getLinkage();
368 } else if (Src->isExternal()) {
369 // If Src is external or if both Src & Drc are external.. Just link the
370 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000371 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000372 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000373 if (Dest->isExternal()) {
374 LinkFromSrc = true;
375 LT = Src->getLinkage();
376 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000377 } else if (Dest->hasExternalWeakLinkage()) {
378 //If the Dest is weak, use the source linkage
379 LinkFromSrc = true;
380 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000381 } else {
382 LinkFromSrc = false;
383 LT = Dest->getLinkage();
384 }
385 } else if (Dest->isExternal() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000386 // If Dest is external but Src is not:
387 LinkFromSrc = true;
388 LT = Src->getLinkage();
389 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
390 if (Src->getLinkage() != Dest->getLinkage())
391 return Error(Err, "Linking globals named '" + Src->getName() +
392 "': can only link appending global with another appending global!");
393 LinkFromSrc = true; // Special cased.
394 LT = Src->getLinkage();
395 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000396 // At this point we know that Dest has LinkOnce, External*, Weak, DLL* linkage.
397 if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
398 Dest->hasExternalWeakLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000399 LinkFromSrc = true;
400 LT = Src->getLinkage();
401 } else {
402 LinkFromSrc = false;
403 LT = Dest->getLinkage();
404 }
405 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000406 // At this point we know that Src has External* or DLL* linkage.
407 if (Src->hasExternalWeakLinkage()) {
408 LinkFromSrc = false;
409 LT = Dest->getLinkage();
410 } else {
411 LinkFromSrc = true;
412 LT = GlobalValue::ExternalLinkage;
413 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000414 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000415 assert((Dest->hasExternalLinkage() ||
416 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000417 Dest->hasDLLExportLinkage() ||
418 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000419 (Src->hasExternalLinkage() ||
420 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000421 Src->hasDLLExportLinkage() ||
422 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000423 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000424 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000425 "': symbol multiply defined!");
426 }
427 return false;
428}
Chris Lattner5c377c52001-10-14 23:29:15 +0000429
430// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000431// them into the dest module.
Chris Lattneraee38ea2004-12-03 22:18:41 +0000432static bool LinkGlobals(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000433 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000434 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5a837de2004-08-04 07:44:58 +0000435 std::map<std::string, GlobalValue*> &GlobalsByName,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000436 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000437 // We will need a module level symbol table if the src module has a module
438 // level symbol table...
Reid Spencer78d033e2007-01-06 07:24:44 +0000439 TypeSymbolTable *TST = &Dest->getTypeSymbolTable();
Misha Brukmanf976c852005-04-21 22:55:34 +0000440
Chris Lattner5c377c52001-10-14 23:29:15 +0000441 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000442 for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
443 I != E; ++I) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000444 GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000445 GlobalVariable *DGV = 0;
Chris Lattner5a837de2004-08-04 07:44:58 +0000446 // Check to see if may have to link the global.
Chris Lattneraad2deb2004-08-04 22:39:54 +0000447 if (SGV->hasName() && !SGV->hasInternalLinkage())
448 if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
449 SGV->getType()->getElementType()))) {
450 std::map<std::string, GlobalValue*>::iterator EGV =
451 GlobalsByName.find(SGV->getName());
452 if (EGV != GlobalsByName.end())
453 DGV = dyn_cast<GlobalVariable>(EGV->second);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000454 if (DGV)
455 // If types don't agree due to opaque types, try to resolve them.
Reid Spencer78d033e2007-01-06 07:24:44 +0000456 RecursiveResolveTypes(SGV->getType(), DGV->getType(), TST, "");
Chris Lattneraad2deb2004-08-04 22:39:54 +0000457 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000458
Chris Lattneraee38ea2004-12-03 22:18:41 +0000459 if (DGV && DGV->hasInternalLinkage())
460 DGV = 0;
461
Andrew Lenharth8753c442006-12-15 17:35:32 +0000462 assert(SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000463 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage() &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000464 "Global must either be external or have an initializer!");
465
Chris Lattnerb324bd72006-11-09 05:18:12 +0000466 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
467 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000468 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
469 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000470
Chris Lattneraee38ea2004-12-03 22:18:41 +0000471 if (!DGV) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000472 // No linking to be performed, simply create an identical version of the
473 // symbol over in the dest module... the initializer will be filled in
474 // later by LinkGlobalInits...
Chris Lattner2719bac2003-04-21 21:15:04 +0000475 GlobalVariable *NewDGV =
476 new GlobalVariable(SGV->getType()->getElementType(),
477 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
478 SGV->getName(), Dest);
Chris Lattner11273152006-06-16 01:24:04 +0000479 // Propagate alignment info.
480 NewDGV->setAlignment(SGV->getAlignment());
481
Chris Lattner2719bac2003-04-21 21:15:04 +0000482 // If the LLVM runtime renamed the global, but it is an externally visible
483 // symbol, DGV must be an existing global with internal linkage. Rename
484 // it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000485 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
486 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000487
488 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000489 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000490 if (SGV->hasAppendingLinkage())
491 // Keep track that this is an appending variable...
492 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattneraee38ea2004-12-03 22:18:41 +0000493 } else if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000494 // No linking is performed yet. Just insert a new copy of the global, and
495 // keep track of the fact that it is an appending variable in the
496 // AppendingVars map. The name is cleared out so that no linkage is
497 // performed.
498 GlobalVariable *NewDGV =
499 new GlobalVariable(SGV->getType()->getElementType(),
500 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
501 "", Dest);
502
Chris Lattner11273152006-06-16 01:24:04 +0000503 // Propagate alignment info.
504 NewDGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
505
Chris Lattner8166e6e2003-05-13 21:33:43 +0000506 // Make sure to remember this mapping...
507 ValueMap.insert(std::make_pair(SGV, NewDGV));
508
509 // Keep track that this is an appending variable...
510 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000511 } else {
Chris Lattner11273152006-06-16 01:24:04 +0000512 // Propagate alignment info.
513 DGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
514
Chris Lattneraee38ea2004-12-03 22:18:41 +0000515 // Otherwise, perform the mapping as instructed by GetLinkageResult. If
516 // the types don't match, and if we are to link from the source, nuke DGV
517 // and create a new one of the appropriate type.
518 if (SGV->getType() != DGV->getType() && LinkFromSrc) {
519 GlobalVariable *NewDGV =
520 new GlobalVariable(SGV->getType()->getElementType(),
521 DGV->isConstant(), DGV->getLinkage());
Chris Lattner11273152006-06-16 01:24:04 +0000522 NewDGV->setAlignment(DGV->getAlignment());
Chris Lattneraee38ea2004-12-03 22:18:41 +0000523 Dest->getGlobalList().insert(DGV, NewDGV);
Reid Spencer4da49122006-12-12 05:05:00 +0000524 DGV->replaceAllUsesWith(
525 ConstantExpr::getBitCast(NewDGV, DGV->getType()));
Chris Lattneraee38ea2004-12-03 22:18:41 +0000526 DGV->eraseFromParent();
527 NewDGV->setName(SGV->getName());
528 DGV = NewDGV;
529 }
530
531 DGV->setLinkage(NewLinkage);
532
533 if (LinkFromSrc) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000534 // Inherit const as appropriate
Chris Lattnere6f8c5a2005-02-12 19:20:28 +0000535 DGV->setConstant(SGV->isConstant());
Chris Lattneraee38ea2004-12-03 22:18:41 +0000536 DGV->setInitializer(0);
537 } else {
538 if (SGV->isConstant() && !DGV->isConstant()) {
Chris Lattnere6f8c5a2005-02-12 19:20:28 +0000539 if (DGV->isExternal())
Chris Lattneraee38ea2004-12-03 22:18:41 +0000540 DGV->setConstant(true);
541 }
Chris Lattnerc8ef1ed2004-12-04 18:54:48 +0000542 SGV->setLinkage(GlobalValue::ExternalLinkage);
543 SGV->setInitializer(0);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000544 }
545
Reid Spencer4da49122006-12-12 05:05:00 +0000546 ValueMap.insert(
547 std::make_pair(SGV, ConstantExpr::getBitCast(DGV, SGV->getType())));
Chris Lattner5c377c52001-10-14 23:29:15 +0000548 }
549 }
550 return false;
551}
552
553
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000554// LinkGlobalInits - Update the initializers in the Dest module now that all
555// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000556static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000557 std::map<const Value*, Value*> &ValueMap,
558 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000559
560 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000561 for (Module::const_global_iterator I = Src->global_begin(),
562 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000563 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000564
565 if (SGV->hasInitializer()) { // Only process initialized GV's
566 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000567 Constant *SInit =
Chris Lattner0033baf2004-11-16 17:12:38 +0000568 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000569
Misha Brukmanf976c852005-04-21 22:55:34 +0000570 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000571 if (DGV->hasInitializer()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000572 if (SGV->hasExternalLinkage()) {
573 if (DGV->getInitializer() != SInit)
Misha Brukmanf976c852005-04-21 22:55:34 +0000574 return Error(Err, "Global Variable Collision on '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000575 ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
Chris Lattner4ad02e72003-04-16 20:28:45 +0000576 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000577 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000578 // Nothing is required, mapped values will take the new global
579 // automatically.
Chris Lattner57cb9882004-02-17 21:56:04 +0000580 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
581 // Nothing is required, mapped values will take the new global
582 // automatically.
Chris Lattner4ad02e72003-04-16 20:28:45 +0000583 } else if (DGV->hasAppendingLinkage()) {
584 assert(0 && "Appending linkage unimplemented!");
585 } else {
586 assert(0 && "Unknown linkage!");
587 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000588 } else {
589 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000590 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000591 }
592 }
593 }
594 return false;
595}
Chris Lattner5c377c52001-10-14 23:29:15 +0000596
Chris Lattner79df7c02002-03-26 18:01:55 +0000597// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000598// without doing function bodies... this just adds external function prototypes
599// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000600//
Chris Lattner79df7c02002-03-26 18:01:55 +0000601static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000602 std::map<const Value*, Value*> &ValueMap,
Reid Spencer78d033e2007-01-06 07:24:44 +0000603 std::map<std::string,
604 GlobalValue*> &GlobalsByName,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000605 std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000606 TypeSymbolTable *TST = &Dest->getTypeSymbolTable();
Misha Brukmanf976c852005-04-21 22:55:34 +0000607
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000608 // Loop over all of the functions in the src module, mapping them over as we
609 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000610 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000611 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000612 Function *DF = 0;
Chris Lattner5a837de2004-08-04 07:44:58 +0000613 if (SF->hasName() && !SF->hasInternalLinkage()) {
614 // Check to see if may have to link the function.
Chris Lattneraad2deb2004-08-04 22:39:54 +0000615 if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
616 std::map<std::string, GlobalValue*>::iterator EF =
617 GlobalsByName.find(SF->getName());
618 if (EF != GlobalsByName.end())
619 DF = dyn_cast<Function>(EF->second);
Reid Spencer78d033e2007-01-06 07:24:44 +0000620 if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), TST, ""))
Chris Lattneraad2deb2004-08-04 22:39:54 +0000621 DF = 0; // FIXME: gross.
622 }
Chris Lattner5a837de2004-08-04 07:44:58 +0000623 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000624
Chris Lattner4ad02e72003-04-16 20:28:45 +0000625 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000626 // Function does not already exist, simply insert an function signature
627 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000628 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
629 SF->getName(), Dest);
Chris Lattnercb9048a2005-05-09 01:09:39 +0000630 NewDF->setCallingConv(SF->getCallingConv());
Chris Lattner2719bac2003-04-21 21:15:04 +0000631
632 // If the LLVM runtime renamed the function, but it is an externally
633 // visible symbol, DF must be an existing function with internal linkage.
634 // Rename it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000635 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
Chris Lattner82b5b212004-08-04 22:29:05 +0000636 ForceRenaming(NewDF, SF->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000637
638 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000639 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000640 } else if (SF->isExternal()) {
641 // If SF is external or if both SF & DF are external.. Just link the
642 // external functions, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000643 if (SF->hasDLLImportLinkage()) {
644 if (DF->isExternal()) {
645 ValueMap.insert(std::make_pair(SF, DF));
646 DF->setLinkage(SF->getLinkage());
647 }
648 } else {
649 ValueMap.insert(std::make_pair(SF, DF));
650 }
651 } else if (DF->isExternal() && !DF->hasDLLImportLinkage()) {
652 // If DF is external but SF is not...
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000653 // Link the external functions, update linkage qualifiers
654 ValueMap.insert(std::make_pair(SF, DF));
655 DF->setLinkage(SF->getLinkage());
Chris Lattner35956552003-10-27 16:39:39 +0000656 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000657 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
Chris Lattner72ac148d2003-10-16 18:29:00 +0000658 ValueMap.insert(std::make_pair(SF, DF));
659
Chris Lattner35956552003-10-27 16:39:39 +0000660 // Linkonce+Weak = Weak
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000661 // *+External Weak = *
662 if ((DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) ||
663 DF->hasExternalWeakLinkage())
Chris Lattner35956552003-10-27 16:39:39 +0000664 DF->setLinkage(SF->getLinkage());
665
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000666
Chris Lattner35956552003-10-27 16:39:39 +0000667 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000668 // At this point we know that SF has LinkOnce or External* linkage.
Chris Lattner72ac148d2003-10-16 18:29:00 +0000669 ValueMap.insert(std::make_pair(SF, DF));
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000670 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage())
671 // Don't inherit linkonce & external weak linkage
Chris Lattner72ac148d2003-10-16 18:29:00 +0000672 DF->setLinkage(SF->getLinkage());
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000673 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000674 return Error(Err, "Functions named '" + SF->getName() +
675 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000676 } else if (SF->hasExternalLinkage()) {
677 // The function is defined in both modules!!
Misha Brukmanf976c852005-04-21 22:55:34 +0000678 return Error(Err, "Function '" +
679 ToStr(SF->getFunctionType(), Src) + "':\"" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000680 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000681 } else {
682 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000683 }
684 }
685 return false;
686}
687
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000688// LinkFunctionBody - Copy the source function over into the dest function and
689// fix up references to values. At this point we know that Dest is an external
690// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000691static bool LinkFunctionBody(Function *Dest, Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000692 std::map<const Value*, Value*> &GlobalMap,
693 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000694 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c377c52001-10-14 23:29:15 +0000695
Chris Lattner0033baf2004-11-16 17:12:38 +0000696 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +0000697 Function::arg_iterator DI = Dest->arg_begin();
698 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000699 I != E; ++I, ++DI) {
700 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000701
702 // Add a mapping to our local map
Chris Lattner0033baf2004-11-16 17:12:38 +0000703 GlobalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000704 }
705
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000706 // Splice the body of the source function into the dest function.
707 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +0000708
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000709 // At this point, all of the instructions and values of the function are now
710 // copied over. The only problem is that they are still referencing values in
711 // the Source function as operands. Loop through all of the operands of the
712 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000713 //
Chris Lattner18961502002-06-25 16:12:52 +0000714 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
715 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
716 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000717 OI != OE; ++OI)
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000718 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner0033baf2004-11-16 17:12:38 +0000719 *OI = RemapOperand(*OI, GlobalMap);
720
721 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000722 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
723 I != E; ++I)
Chris Lattner0033baf2004-11-16 17:12:38 +0000724 GlobalMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +0000725
726 return false;
727}
728
729
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000730// LinkFunctionBodies - Link in the function bodies that are defined in the
731// source module into the DestModule. This consists basically of copying the
732// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000733static bool LinkFunctionBodies(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000734 std::map<const Value*, Value*> &ValueMap,
735 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000736
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000737 // Loop over all of the functions in the src module, mapping them over as we
738 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000739 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Chris Lattner18961502002-06-25 16:12:52 +0000740 if (!SF->isExternal()) { // No body if function is external
741 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000742
Chris Lattner18961502002-06-25 16:12:52 +0000743 // DF not external SF external?
Chris Lattner35956552003-10-27 16:39:39 +0000744 if (DF->isExternal()) {
745 // Only provide the function body if there isn't one already.
746 if (LinkFunctionBody(DF, SF, ValueMap, Err))
747 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000748 }
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000749 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000750 }
751 return false;
752}
753
Chris Lattner8166e6e2003-05-13 21:33:43 +0000754// LinkAppendingVars - If there were any appending global variables, link them
755// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000756static bool LinkAppendingVars(Module *M,
757 std::multimap<std::string, GlobalVariable *> &AppendingVars,
758 std::string *ErrorMsg) {
759 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +0000760
Chris Lattner8166e6e2003-05-13 21:33:43 +0000761 // Loop over the multimap of appending vars, processing any variables with the
762 // same name, forming a new appending global variable with both of the
763 // initializers merged together, then rewrite references to the old variables
764 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000765 std::vector<Constant*> Inits;
766 while (AppendingVars.size() > 1) {
767 // Get the first two elements in the map...
768 std::multimap<std::string,
769 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
770
771 // If the first two elements are for different names, there is no pair...
772 // Otherwise there is a pair, so link them together...
773 if (First->first == Second->first) {
774 GlobalVariable *G1 = First->second, *G2 = Second->second;
775 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
776 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +0000777
Chris Lattner8166e6e2003-05-13 21:33:43 +0000778 // Check to see that they two arrays agree on type...
779 if (T1->getElementType() != T2->getElementType())
780 return Error(ErrorMsg,
781 "Appending variables with different element types need to be linked!");
782 if (G1->isConstant() != G2->isConstant())
783 return Error(ErrorMsg,
784 "Appending variables linked with different const'ness!");
785
786 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
787 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
788
Chris Lattnered74a4e2005-12-06 17:30:58 +0000789 G1->setName(""); // Clear G1's name in case of a conflict!
790
Chris Lattner8166e6e2003-05-13 21:33:43 +0000791 // Create the new global variable...
792 GlobalVariable *NG =
793 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
794 /*init*/0, First->first, M);
795
796 // Merge the initializer...
797 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +0000798 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
799 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000800 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +0000801 } else {
802 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
803 Constant *CV = Constant::getNullValue(T1->getElementType());
804 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
805 Inits.push_back(CV);
806 }
807 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
808 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000809 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +0000810 } else {
811 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
812 Constant *CV = Constant::getNullValue(T2->getElementType());
813 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
814 Inits.push_back(CV);
815 }
Chris Lattner8166e6e2003-05-13 21:33:43 +0000816 NG->setInitializer(ConstantArray::get(NewType, Inits));
817 Inits.clear();
818
819 // Replace any uses of the two global variables with uses of the new
820 // global...
821
822 // FIXME: This should rewrite simple/straight-forward uses such as
823 // getelementptr instructions to not use the Cast!
Reid Spencer4da49122006-12-12 05:05:00 +0000824 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
825 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000826
827 // Remove the two globals from the module now...
828 M->getGlobalList().erase(G1);
829 M->getGlobalList().erase(G2);
830
831 // Put the new global into the AppendingVars map so that we can handle
832 // linking of more than two vars...
833 Second->second = NG;
834 }
835 AppendingVars.erase(First);
836 }
837
838 return false;
839}
Chris Lattner52f7e902001-10-13 07:03:50 +0000840
841
842// LinkModules - This function links two modules together, with the resulting
843// left module modified to be the composite of the two input modules. If an
844// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000845// the problem. Upon failure, the Dest module could be in a modified state, and
846// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +0000847bool
Reid Spencer0ba9e212004-12-13 03:00:16 +0000848Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +0000849 assert(Dest != 0 && "Invalid Destination module");
850 assert(Src != 0 && "Invalid Source Module");
851
Chris Lattner873c5e72003-08-24 19:26:42 +0000852 if (Dest->getEndianness() == Module::AnyEndianness)
853 Dest->setEndianness(Src->getEndianness());
854 if (Dest->getPointerSize() == Module::AnyPointerSize)
855 Dest->setPointerSize(Src->getPointerSize());
Chris Lattner152f19a2004-12-10 20:26:15 +0000856 if (Dest->getTargetTriple().empty())
857 Dest->setTargetTriple(Src->getTargetTriple());
Chris Lattner873c5e72003-08-24 19:26:42 +0000858
859 if (Src->getEndianness() != Module::AnyEndianness &&
860 Dest->getEndianness() != Src->getEndianness())
Bill Wendlinge8156192006-12-07 01:30:32 +0000861 cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000862 if (Src->getPointerSize() != Module::AnyPointerSize &&
863 Dest->getPointerSize() != Src->getPointerSize())
Bill Wendlinge8156192006-12-07 01:30:32 +0000864 cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +0000865 if (!Src->getTargetTriple().empty() &&
866 Dest->getTargetTriple() != Src->getTargetTriple())
Bill Wendlinge8156192006-12-07 01:30:32 +0000867 cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukmanf976c852005-04-21 22:55:34 +0000868
Chris Lattner66316012006-01-24 04:14:29 +0000869 if (!Src->getModuleInlineAsm().empty()) {
870 if (Dest->getModuleInlineAsm().empty())
871 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +0000872 else
Chris Lattner66316012006-01-24 04:14:29 +0000873 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
874 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +0000875 }
876
Reid Spencer719012d2004-11-25 09:29:44 +0000877 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +0000878 // from the source module. There's no opportunity for duplicates here as the
879 // Module ensures that duplicate insertions are discarded.
880 Module::lib_iterator SI = Src->lib_begin();
881 Module::lib_iterator SE = Src->lib_end();
882 while ( SI != SE ) {
883 Dest->addLibrary(*SI);
884 ++SI;
885 }
886
Chris Lattner2c236f32001-11-03 05:18:24 +0000887 // LinkTypes - Go through the symbol table of the Src module and see if any
888 // types are named in the src module that are not named in the Dst module.
889 // Make sure there are no type name conflicts.
Chris Lattner2c236f32001-11-03 05:18:24 +0000890 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
891
Chris Lattner5c377c52001-10-14 23:29:15 +0000892 // ValueMap - Mapping of values from what they used to be in Src, to what they
893 // are now in Dest.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000894 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000895
Chris Lattner8166e6e2003-05-13 21:33:43 +0000896 // AppendingVars - Keep track of global variables in the destination module
897 // with appending linkage. After the module is linked together, they are
898 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000899 std::multimap<std::string, GlobalVariable *> AppendingVars;
900
Chris Lattner5a837de2004-08-04 07:44:58 +0000901 // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
902 // linking by separating globals by type. Until PR411 is fixed, we replicate
903 // it's functionality here.
904 std::map<std::string, GlobalValue*> GlobalsByName;
905
Chris Lattner11273152006-06-16 01:24:04 +0000906 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
907 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +0000908 // Add all of the appending globals already in the Dest module to
909 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +0000910 if (I->hasAppendingLinkage())
911 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000912
Chris Lattner5a837de2004-08-04 07:44:58 +0000913 // Keep track of all globals by name.
914 if (!I->hasInternalLinkage() && I->hasName())
915 GlobalsByName[I->getName()] = I;
916 }
917
918 // Keep track of all globals by name.
919 for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
920 if (!I->hasInternalLinkage() && I->hasName())
921 GlobalsByName[I->getName()] = I;
922
Chris Lattner8166e6e2003-05-13 21:33:43 +0000923 // Insert all of the globals in src into the Dest module... without linking
924 // initializers (which could refer to functions not yet mapped over).
Chris Lattner5a837de2004-08-04 07:44:58 +0000925 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
926 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000927
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000928 // Link the functions together between the two modules, without doing function
929 // bodies... this just adds external function prototypes to the Dest
930 // function... We do this so that when we begin processing function bodies,
931 // all of the global values that may be referenced are available in our
932 // ValueMap.
Chris Lattner5a837de2004-08-04 07:44:58 +0000933 if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
934 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000935
Chris Lattner6cdf1972002-07-18 00:13:08 +0000936 // Update the initializers in the Dest module now that all globals that may
937 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +0000938 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
939
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000940 // Link in the function bodies that are defined in the source module into the
941 // DestModule. This consists basically of copying the function over and
942 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +0000943 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000944
Chris Lattner8166e6e2003-05-13 21:33:43 +0000945 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000946 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
947
Reid Spencer57a0efa2004-09-11 04:25:17 +0000948 // If the source library's module id is in the dependent library list of the
949 // destination library, remove it since that module is now linked in.
950 sys::Path modId;
Reid Spencerdd04df02005-07-07 23:21:43 +0000951 modId.set(Src->getModuleIdentifier());
Reid Spencer07adb282004-11-05 22:15:36 +0000952 if (!modId.isEmpty())
953 Dest->removeLibrary(modId.getBasename());
Reid Spencer57a0efa2004-09-11 04:25:17 +0000954
Chris Lattner52f7e902001-10-13 07:03:50 +0000955 return false;
956}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000957
Reid Spencer567bc2c2004-05-25 08:52:20 +0000958// vim: sw=2