blob: af430bd70b795992cfccb934758df5213c82e8a4 [file] [log] [blame]
Chris Lattner52f7e902001-10-13 07:03:50 +00001//===- Linker.cpp - Module Linker Implementation --------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000019#include "llvm/Transforms/Utils/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"
Chris Lattner5c377c52001-10-14 23:29:15 +000024#include "llvm/iOther.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000025#include "llvm/Assembly/Writer.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner5c377c52001-10-14 23:29:15 +000028// Error - Simple wrapper function to conditionally assign to E and return true.
29// This just makes error return conditions a little bit simpler...
30//
Chris Lattner8166e6e2003-05-13 21:33:43 +000031static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000032 if (E) *E = Message;
33 return true;
34}
35
John Criswell700867b2003-11-04 15:22:26 +000036//
37// Function: ResolveTypes()
38//
39// Description:
40// Attempt to link the two specified types together.
41//
42// Inputs:
43// DestTy - The type to which we wish to resolve.
44// SrcTy - The original type which we want to resolve.
45// Name - The name of the type.
46//
47// Outputs:
48// DestST - The symbol table in which the new type should be placed.
49//
50// Return value:
51// true - There is an error and the types cannot yet be linked.
52// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000053//
Chris Lattnere76c57a2003-08-22 06:07:12 +000054static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
55 SymbolTable *DestST, const std::string &Name) {
56 if (DestTy == SrcTy) return false; // If already equal, noop
57
Chris Lattner4c00e532003-05-15 16:30:55 +000058 // Does the type already exist in the module?
59 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000060 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
61 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000062 } else {
63 return true; // Cannot link types... neither is opaque and not-equal
64 }
65 } else { // Type not in dest module. Add it now.
66 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000067 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
68 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000069 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000070 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000071 }
72 return false;
73}
74
Chris Lattner43f4ba82003-08-22 19:12:55 +000075static const FunctionType *getFT(const PATypeHolder &TH) {
76 return cast<FunctionType>(TH.get());
77}
Chris Lattner9732be72003-08-22 20:16:48 +000078static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000079 return cast<StructType>(TH.get());
80}
Chris Lattnere76c57a2003-08-22 06:07:12 +000081
82// RecursiveResolveTypes - This is just like ResolveTypes, except that it
83// recurses down into derived types, merging the used types if the parent types
84// are compatible.
85//
Chris Lattnere3092c92003-08-23 21:25:54 +000086static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
87 const PATypeHolder &SrcTy,
88 SymbolTable *DestST, const std::string &Name,
89 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000090 const Type *SrcTyT = SrcTy.get();
91 const Type *DestTyT = DestTy.get();
92 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +000093
94 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000095 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
96 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +000097
98 // Two types cannot be resolved together if they are of different primitive
99 // type. For example, we cannot resolve an int to a float.
Chris Lattner43f4ba82003-08-22 19:12:55 +0000100 if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000101
102 // Otherwise, resolve the used type used by this derived type...
Chris Lattner43f4ba82003-08-22 19:12:55 +0000103 switch (DestTyT->getPrimitiveID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000104 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000105 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000106 cast<FunctionType>(SrcTyT)->isVarArg() ||
107 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
108 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000109 return true;
110 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000111 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
112 getFT(SrcTy)->getContainedType(i), DestST, "",
113 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000114 return true;
115 return false;
116 }
117 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000118 if (getST(DestTy)->getNumContainedTypes() !=
119 getST(SrcTy)->getNumContainedTypes()) return 1;
120 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000121 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
122 getST(SrcTy)->getContainedType(i), DestST, "",
123 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000124 return true;
125 return false;
126 }
127 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000128 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
129 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000130 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000131 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
132 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000133 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000134 case Type::PointerTyID: {
135 // If this is a pointer type, check to see if we have already seen it. If
136 // so, we are in a recursive branch. Cut off the search now. We cannot use
137 // an associative container for this search, because the type pointers (keys
138 // in the container) change whenever types get resolved...
139 //
140 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
141 if (Pointers[i].first == DestTy)
142 return Pointers[i].second != SrcTy;
143
144 // Otherwise, add the current pointers to the vector to stop recursion on
145 // this pair.
146 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
147 bool Result =
148 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
149 cast<PointerType>(SrcTy.get())->getElementType(),
150 DestST, "", Pointers);
151 Pointers.pop_back();
152 return Result;
153 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000154 default: assert(0 && "Unexpected type!"); return true;
155 }
156}
157
Chris Lattnere3092c92003-08-23 21:25:54 +0000158static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
159 const PATypeHolder &SrcTy,
160 SymbolTable *DestST, const std::string &Name){
161 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
162 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
163}
164
Chris Lattnere76c57a2003-08-22 06:07:12 +0000165
Chris Lattner2c236f32001-11-03 05:18:24 +0000166// LinkTypes - Go through the symbol table of the Src module and see if any
167// types are named in the src module that are not named in the Dst module.
168// Make sure there are no type name conflicts.
169//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000170static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000171 SymbolTable *DestST = &Dest->getSymbolTable();
172 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000173
174 // Look for a type plane for Type's...
175 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
176 if (PI == SrcST->end()) return false; // No named types, do nothing.
177
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000178 // Some types cannot be resolved immediately because they depend on other
179 // types being resolved to each other first. This contains a list of types we
180 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000181 std::vector<std::string> DelayedTypesToResolve;
182
Chris Lattner2c236f32001-11-03 05:18:24 +0000183 const SymbolTable::VarMap &VM = PI->second;
184 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
185 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000186 const std::string &Name = I->first;
Chris Lattner4c00e532003-05-15 16:30:55 +0000187 Type *RHS = cast<Type>(I->second);
Chris Lattner2c236f32001-11-03 05:18:24 +0000188
189 // Check to see if this type name is already in the dest module...
Chris Lattner4c00e532003-05-15 16:30:55 +0000190 Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000191
Chris Lattner4c00e532003-05-15 16:30:55 +0000192 if (ResolveTypes(Entry, RHS, DestST, Name)) {
193 // They look different, save the types 'till later to resolve.
194 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000195 }
196 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000197
198 // Iteratively resolve types while we can...
199 while (!DelayedTypesToResolve.empty()) {
200 // Loop over all of the types, attempting to resolve them if possible...
201 unsigned OldSize = DelayedTypesToResolve.size();
202
Chris Lattnere76c57a2003-08-22 06:07:12 +0000203 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000204 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
205 const std::string &Name = DelayedTypesToResolve[i];
206 Type *T1 = cast<Type>(VM.find(Name)->second);
207 Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
208 if (!ResolveTypes(T2, T1, DestST, Name)) {
209 // We are making progress!
210 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
211 --i;
212 }
213 }
214
215 // Did we not eliminate any types?
216 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000217 // Attempt to resolve subelements of types. This allows us to merge these
218 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000219 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
220 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattner43f4ba82003-08-22 19:12:55 +0000221 PATypeHolder T1(cast<Type>(VM.find(Name)->second));
222 PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000223
224 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
225 // We are making progress!
226 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
227
228 // Go back to the main loop, perhaps we can resolve directly by name
229 // now...
230 break;
231 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000232 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000233
234 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000235 // Report the warning and delete one of the names.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000236 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000237 const std::string &Name = DelayedTypesToResolve.back();
238
239 const Type *T1 = cast<Type>(VM.find(Name)->second);
240 const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
241 std::cerr << "WARNING: Type conflict between types named '" << Name
Chris Lattneradbc0b52003-11-20 18:23:14 +0000242 << "'.\n Src='";
243 WriteTypeSymbolic(std::cerr, T1, Src);
244 std::cerr << "'.\n Dest='";
245 WriteTypeSymbolic(std::cerr, T2, Dest);
246 std::cerr << "'\n";
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000247
248 // Remove the symbol name from the destination.
249 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000250 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000251 }
252 }
253
254
Chris Lattner2c236f32001-11-03 05:18:24 +0000255 return false;
256}
257
Chris Lattner5c2d3352003-01-30 19:53:34 +0000258static void PrintMap(const std::map<const Value*, Value*> &M) {
259 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000260 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000261 std::cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000262 I->first->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000263 std::cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000264 I->second->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000265 std::cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000266 }
267}
268
269
Chris Lattner5c377c52001-10-14 23:29:15 +0000270// RemapOperand - Use LocalMap and GlobalMap to convert references from one
271// module to another. This is somewhat sophisticated in that it can
272// automatically handle constant references correctly as well...
273//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000274static Value *RemapOperand(const Value *In,
275 std::map<const Value*, Value*> &LocalMap,
276 std::map<const Value*, Value*> *GlobalMap) {
277 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
Chris Lattner5c377c52001-10-14 23:29:15 +0000278 if (I != LocalMap.end()) return I->second;
279
280 if (GlobalMap) {
281 I = GlobalMap->find(In);
282 if (I != GlobalMap->end()) return I->second;
283 }
284
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000285 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattner18961502002-06-25 16:12:52 +0000286 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattner6cdf1972002-07-18 00:13:08 +0000287 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000288 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000289
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000290 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000291
Chris Lattner18961502002-06-25 16:12:52 +0000292 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000293 const std::vector<Use> &Ops = CPA->getValues();
294 std::vector<Constant*> Operands(Ops.size());
Chris Lattnere306d942002-07-18 02:31:03 +0000295 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000296 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000297 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
298 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000299 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000300 const std::vector<Use> &Ops = CPS->getValues();
301 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000302 for (unsigned i = 0; i < Ops.size(); ++i)
303 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000304 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
305 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
306 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000307 Result = const_cast<Constant*>(CPV);
308 } else if (const ConstantPointerRef *CPR =
309 dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000310 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000311 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000312 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000313 if (CE->getOpcode() == Instruction::GetElementPtr) {
314 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
315 std::vector<Constant*> Indices;
316 Indices.reserve(CE->getNumOperands()-1);
317 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
318 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
319 LocalMap, GlobalMap)));
320
321 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
322 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000323 // Cast instruction
324 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000325 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000326 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000327 } else if (CE->getOpcode() == Instruction::Shl ||
328 CE->getOpcode() == Instruction::Shr) { // Shift
329 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
330 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
331 Result = ConstantExpr::getShift(CE->getOpcode(), cast<Constant>(V1),
332 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000333 } else if (CE->getNumOperands() == 2) {
334 // Binary operator...
335 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
336 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
337
338 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000339 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000340 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000341 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000342 }
343
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000344 } else {
345 assert(0 && "Unknown type of derived type constant value!");
346 }
347
348 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000349 if (GlobalMap)
350 GlobalMap->insert(std::make_pair(In, Result));
351 else
352 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000353 return Result;
354 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000355
Chris Lattner5c2d3352003-01-30 19:53:34 +0000356 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000357 PrintMap(LocalMap);
358
359 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000360 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000361 PrintMap(*GlobalMap);
362 }
363
Chris Lattner5c2d3352003-01-30 19:53:34 +0000364 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000365 assert(0 && "Couldn't remap value!");
366 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000367}
368
Chris Lattnerfcd02342003-08-23 20:31:10 +0000369/// FindGlobalNamed - Look in the specified symbol table for a global with the
370/// specified name and type. If an exactly matching global does not exist, see
371/// if there is a global which is "type compatible" with the specified
372/// name/type. This allows us to resolve things like '%x = global int*' with
373/// '%x = global opaque*'.
374///
375static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
376 SymbolTable *ST) {
377 // See if an exact match exists in the symbol table...
378 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
379
380 // It doesn't exist exactly, scan through all of the type planes in the symbol
381 // table, checking each of them for a type-compatible version.
382 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000383 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
Chris Lattner77c5f732003-08-24 19:30:20 +0000384 if (I->first != Type::TypeTy) {
Chris Lattnerf44c6052003-08-23 21:32:24 +0000385 SymbolTable::VarMap &VM = I->second;
John Criswell700867b2003-11-04 15:22:26 +0000386
Chris Lattnerf44c6052003-08-23 21:32:24 +0000387 // Does this type plane contain an entry with the specified name?
388 SymbolTable::type_iterator TI = VM.find(Name);
389 if (TI != VM.end()) {
John Criswell700867b2003-11-04 15:22:26 +0000390 //
391 // Ensure that this type if placed correctly into the symbol table.
392 //
393 assert(TI->second->getType() == I->first && "Type conflict!");
394
395 //
396 // Save a reference to the new type. Resolving the type can modify the
397 // symbol table, invalidating the TI variable.
398 //
399 Value *ValPtr = TI->second;
400
401 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000402 // Determine whether we can fold the two types together, resolving them.
403 // If so, we can use this value.
John Criswell700867b2003-11-04 15:22:26 +0000404 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000405 if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
John Criswell700867b2003-11-04 15:22:26 +0000406 return cast<GlobalValue>(ValPtr);
Chris Lattnerf44c6052003-08-23 21:32:24 +0000407 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000408 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000409 return 0; // Otherwise, nothing could be found.
410}
411
Chris Lattner5c377c52001-10-14 23:29:15 +0000412
413// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000414// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000415//
416static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000417 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000418 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000419 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000420 // We will need a module level symbol table if the src module has a module
421 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000422 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000423
424 // Loop over all of the globals in the src module, mapping them over as we go
425 //
426 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000427 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000428 GlobalVariable *DGV = 0;
429 if (SGV->hasName()) {
430 // A same named thing is a global variable, because the only two things
Chris Lattner79df7c02002-03-26 18:01:55 +0000431 // that may be in a module level symbol table are Global Vars and
432 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000433 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000434 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
435 SGV->getType(), ST));
Chris Lattner4ad02e72003-04-16 20:28:45 +0000436 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000437
Chris Lattner4ad02e72003-04-16 20:28:45 +0000438 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
439 "Global must either be external or have an initializer!");
440
Chris Lattner0fec08e2003-04-21 21:07:05 +0000441 bool SGExtern = SGV->isExternal();
442 bool DGExtern = DGV ? DGV->isExternal() : false;
443
Chris Lattner4ad02e72003-04-16 20:28:45 +0000444 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
445 // No linking to be performed, simply create an identical version of the
446 // symbol over in the dest module... the initializer will be filled in
447 // later by LinkGlobalInits...
448 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000449 GlobalVariable *NewDGV =
450 new GlobalVariable(SGV->getType()->getElementType(),
451 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
452 SGV->getName(), Dest);
453
454 // If the LLVM runtime renamed the global, but it is an externally visible
455 // symbol, DGV must be an existing global with internal linkage. Rename
456 // it.
457 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
458 assert(DGV && DGV->getName() == SGV->getName() &&
459 DGV->hasInternalLinkage());
460 DGV->setName("");
461 NewDGV->setName(SGV->getName()); // Force the name back
462 DGV->setName(SGV->getName()); // This will cause a renaming
463 assert(NewDGV->getName() == SGV->getName() &&
464 DGV->getName() != SGV->getName());
465 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000466
467 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000468 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000469 if (SGV->hasAppendingLinkage())
470 // Keep track that this is an appending variable...
471 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
472
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000473 } else if (SGV->isExternal()) {
474 // If SGV is external or if both SGV & DGV are external.. Just link the
475 // external globals, we aren't adding anything.
476 ValueMap.insert(std::make_pair(SGV, DGV));
477
478 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
479 ValueMap.insert(std::make_pair(SGV, DGV));
480 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
Chris Lattner35956552003-10-27 16:39:39 +0000481 } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000482 // At this point we know that DGV has LinkOnce, Appending, Weak, or
483 // External linkage. If DGV is Appending, this is an error.
484 if (DGV->hasAppendingLinkage())
485 return Error(Err, "Linking globals named '" + SGV->getName() +
486 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000487
488 if (SGV->isConstant() != DGV->isConstant())
489 return Error(Err, "Global Variable Collision on '" +
490 SGV->getType()->getDescription() + " %" + SGV->getName() +
491 "' - Global variables differ in const'ness");
492
Chris Lattner72ac148d2003-10-16 18:29:00 +0000493 // Otherwise, just perform the link.
494 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattner35956552003-10-27 16:39:39 +0000495
496 // Linkonce+Weak = Weak
497 if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
498 DGV->setLinkage(SGV->getLinkage());
499
500 } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000501 // At this point we know that SGV has LinkOnce, Appending, or External
502 // linkage. If SGV is Appending, this is an error.
503 if (SGV->hasAppendingLinkage())
504 return Error(Err, "Linking globals named '" + SGV->getName() +
505 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000506
507 if (SGV->isConstant() != DGV->isConstant())
508 return Error(Err, "Global Variable Collision on '" +
509 SGV->getType()->getDescription() + " %" + SGV->getName() +
510 "' - Global variables differ in const'ness");
511
Chris Lattner72ac148d2003-10-16 18:29:00 +0000512 if (!SGV->hasLinkOnceLinkage())
513 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
514 ValueMap.insert(std::make_pair(SGV, DGV));
515
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000516 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000517 return Error(Err, "Global variables named '" + SGV->getName() +
518 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000519 } else if (SGV->hasExternalLinkage()) {
520 // Allow linking two exactly identical external global variables...
Chris Lattnerf85770c2003-10-21 21:52:20 +0000521 if (SGV->isConstant() != DGV->isConstant())
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000522 return Error(Err, "Global Variable Collision on '" +
523 SGV->getType()->getDescription() + " %" + SGV->getName() +
524 "' - Global variables differ in const'ness");
Chris Lattnerf85770c2003-10-21 21:52:20 +0000525
526 if (SGV->getInitializer() != DGV->getInitializer())
527 return Error(Err, "Global Variable Collision on '" +
528 SGV->getType()->getDescription() + " %" + SGV->getName() +
529 "' - External linkage globals have different initializers");
530
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000531 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000532 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000533 // No linking is performed yet. Just insert a new copy of the global, and
534 // keep track of the fact that it is an appending variable in the
535 // AppendingVars map. The name is cleared out so that no linkage is
536 // performed.
537 GlobalVariable *NewDGV =
538 new GlobalVariable(SGV->getType()->getElementType(),
539 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
540 "", Dest);
541
542 // Make sure to remember this mapping...
543 ValueMap.insert(std::make_pair(SGV, NewDGV));
544
545 // Keep track that this is an appending variable...
546 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000547 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000548 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000549 }
550 }
551 return false;
552}
553
554
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000555// LinkGlobalInits - Update the initializers in the Dest module now that all
556// globals that may be referenced are in Dest.
557//
558static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000559 std::map<const Value*, Value*> &ValueMap,
560 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000561
562 // Loop over all of the globals in the src module, mapping them over as we go
563 //
564 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000565 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000566
567 if (SGV->hasInitializer()) { // Only process initialized GV's
568 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000569 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000570 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000571
572 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000573 if (DGV->hasInitializer()) {
574 assert(SGV->getLinkage() == DGV->getLinkage());
575 if (SGV->hasExternalLinkage()) {
576 if (DGV->getInitializer() != SInit)
577 return Error(Err, "Global Variable Collision on '" +
578 SGV->getType()->getDescription() +"':%"+SGV->getName()+
579 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000580 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000581 // Nothing is required, mapped values will take the new global
582 // automatically.
583 } 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,
603 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000604 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000605
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000606 // Loop over all of the functions in the src module, mapping them over as we
607 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000608 //
609 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000610 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000611 Function *DF = 0;
612 if (SF->hasName())
Chris Lattner79df7c02002-03-26 18:01:55 +0000613 // The same named thing is a Function, because the only two things
614 // that may be in a module level symbol table are Global Vars and
615 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000616 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000617 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
618 ST));
Chris Lattner5c377c52001-10-14 23:29:15 +0000619
Chris Lattner4ad02e72003-04-16 20:28:45 +0000620 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000621 // Function does not already exist, simply insert an function signature
622 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000623 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
624 SF->getName(), Dest);
625
626 // If the LLVM runtime renamed the function, but it is an externally
627 // visible symbol, DF must be an existing function with internal linkage.
628 // Rename it.
629 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
630 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
631 DF->setName("");
632 NewDF->setName(SF->getName()); // Force the name back
633 DF->setName(SF->getName()); // This will cause a renaming
634 assert(NewDF->getName() == SF->getName() &&
635 DF->getName() != SF->getName());
636 }
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.
643 ValueMap.insert(std::make_pair(SF, DF));
644 } else if (DF->isExternal()) { // If DF is external but SF is not...
645 // Link the external functions, update linkage qualifiers
646 ValueMap.insert(std::make_pair(SF, DF));
647 DF->setLinkage(SF->getLinkage());
648
Chris Lattner35956552003-10-27 16:39:39 +0000649 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000650 // At this point we know that DF has LinkOnce, Weak, or External linkage.
651 ValueMap.insert(std::make_pair(SF, DF));
652
Chris Lattner35956552003-10-27 16:39:39 +0000653 // Linkonce+Weak = Weak
654 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
655 DF->setLinkage(SF->getLinkage());
656
657 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000658 // At this point we know that SF has LinkOnce or External linkage.
659 ValueMap.insert(std::make_pair(SF, DF));
660 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
661 DF->setLinkage(SF->getLinkage());
662
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!!
668 return Error(Err, "Function '" +
669 SF->getFunctionType()->getDescription() + "':\"" +
670 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 Lattner5c377c52001-10-14 23:29:15 +0000681//
Chris Lattner79df7c02002-03-26 18:01:55 +0000682static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000683 std::map<const Value*, Value*> &GlobalMap,
684 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000685 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000686 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000687
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000688 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000689 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000690 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000691 I != E; ++I, ++DI) {
692 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000693
694 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000695 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000696 }
697
698 // Loop over all of the basic blocks, copying the instructions over...
699 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000700 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000701 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000702 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
703 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000704
705 // Loop over all of the instructions in the src basic block, copying them
706 // over. Note that this is broken in a strict sense because the cloned
707 // instructions will still be referencing values in the Src module, not
708 // the remapped values. In our case, however, we will not get caught and
709 // so we can delay patching the values up until later...
710 //
Chris Lattner18961502002-06-25 16:12:52 +0000711 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000712 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000713 Instruction *DI = II->clone();
714 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000715 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000716 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000717 }
718 }
719
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000720 // At this point, all of the instructions and values of the function are now
721 // copied over. The only problem is that they are still referencing values in
722 // the Source function as operands. Loop through all of the operands of the
723 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000724 //
Chris Lattner18961502002-06-25 16:12:52 +0000725 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
726 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
727 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000728 OI != OE; ++OI)
729 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000730
731 return false;
732}
733
734
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000735// LinkFunctionBodies - Link in the function bodies that are defined in the
736// source module into the DestModule. This consists basically of copying the
737// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000738//
Chris Lattner79df7c02002-03-26 18:01:55 +0000739static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000740 std::map<const Value*, Value*> &ValueMap,
741 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000742
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000743 // Loop over all of the functions in the src module, mapping them over as we
744 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000745 //
Chris Lattner18961502002-06-25 16:12:52 +0000746 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
747 if (!SF->isExternal()) { // No body if function is external
748 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000749
Chris Lattner18961502002-06-25 16:12:52 +0000750 // DF not external SF external?
Chris Lattner35956552003-10-27 16:39:39 +0000751 if (DF->isExternal()) {
752 // Only provide the function body if there isn't one already.
753 if (LinkFunctionBody(DF, SF, ValueMap, Err))
754 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000755 }
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000756 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000757 }
758 return false;
759}
760
Chris Lattner8166e6e2003-05-13 21:33:43 +0000761// LinkAppendingVars - If there were any appending global variables, link them
762// together now. Return true on error.
763//
764static bool LinkAppendingVars(Module *M,
765 std::multimap<std::string, GlobalVariable *> &AppendingVars,
766 std::string *ErrorMsg) {
767 if (AppendingVars.empty()) return false; // Nothing to do.
768
769 // Loop over the multimap of appending vars, processing any variables with the
770 // same name, forming a new appending global variable with both of the
771 // initializers merged together, then rewrite references to the old variables
772 // and delete them.
773 //
774 std::vector<Constant*> Inits;
775 while (AppendingVars.size() > 1) {
776 // Get the first two elements in the map...
777 std::multimap<std::string,
778 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
779
780 // If the first two elements are for different names, there is no pair...
781 // Otherwise there is a pair, so link them together...
782 if (First->first == Second->first) {
783 GlobalVariable *G1 = First->second, *G2 = Second->second;
784 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
785 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
786
787 // Check to see that they two arrays agree on type...
788 if (T1->getElementType() != T2->getElementType())
789 return Error(ErrorMsg,
790 "Appending variables with different element types need to be linked!");
791 if (G1->isConstant() != G2->isConstant())
792 return Error(ErrorMsg,
793 "Appending variables linked with different const'ness!");
794
795 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
796 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
797
798 // Create the new global variable...
799 GlobalVariable *NG =
800 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
801 /*init*/0, First->first, M);
802
803 // Merge the initializer...
804 Inits.reserve(NewSize);
805 ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
806 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
807 Inits.push_back(cast<Constant>(I->getValues()[i]));
808 I = cast<ConstantArray>(G2->getInitializer());
809 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
810 Inits.push_back(cast<Constant>(I->getValues()[i]));
811 NG->setInitializer(ConstantArray::get(NewType, Inits));
812 Inits.clear();
813
814 // Replace any uses of the two global variables with uses of the new
815 // global...
816
817 // FIXME: This should rewrite simple/straight-forward uses such as
818 // getelementptr instructions to not use the Cast!
819 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
820 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
821 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
822
823 // Remove the two globals from the module now...
824 M->getGlobalList().erase(G1);
825 M->getGlobalList().erase(G2);
826
827 // Put the new global into the AppendingVars map so that we can handle
828 // linking of more than two vars...
829 Second->second = NG;
830 }
831 AppendingVars.erase(First);
832 }
833
834 return false;
835}
Chris Lattner52f7e902001-10-13 07:03:50 +0000836
837
838// LinkModules - This function links two modules together, with the resulting
839// left module modified to be the composite of the two input modules. If an
840// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000841// the problem. Upon failure, the Dest module could be in a modified state, and
842// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000843//
Chris Lattnerf7703df2004-01-09 06:12:26 +0000844bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Chris Lattner873c5e72003-08-24 19:26:42 +0000845 if (Dest->getEndianness() == Module::AnyEndianness)
846 Dest->setEndianness(Src->getEndianness());
847 if (Dest->getPointerSize() == Module::AnyPointerSize)
848 Dest->setPointerSize(Src->getPointerSize());
849
850 if (Src->getEndianness() != Module::AnyEndianness &&
851 Dest->getEndianness() != Src->getEndianness())
Chris Lattner43a99942003-04-22 19:13:20 +0000852 std::cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000853 if (Src->getPointerSize() != Module::AnyPointerSize &&
854 Dest->getPointerSize() != Src->getPointerSize())
Chris Lattner43a99942003-04-22 19:13:20 +0000855 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000856
857 // LinkTypes - Go through the symbol table of the Src module and see if any
858 // types are named in the src module that are not named in the Dst module.
859 // Make sure there are no type name conflicts.
860 //
861 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
862
Chris Lattner5c377c52001-10-14 23:29:15 +0000863 // ValueMap - Mapping of values from what they used to be in Src, to what they
864 // are now in Dest.
865 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000866 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000867
Chris Lattner8166e6e2003-05-13 21:33:43 +0000868 // AppendingVars - Keep track of global variables in the destination module
869 // with appending linkage. After the module is linked together, they are
870 // appended and the module is rewritten.
871 //
872 std::multimap<std::string, GlobalVariable *> AppendingVars;
873
874 // Add all of the appending globals already in the Dest module to
875 // AppendingVars.
876 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
Chris Lattnerf4146462003-05-14 12:11:51 +0000877 if (I->hasAppendingLinkage())
878 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000879
880 // Insert all of the globals in src into the Dest module... without linking
881 // initializers (which could refer to functions not yet mapped over).
882 //
883 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000884
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000885 // Link the functions together between the two modules, without doing function
886 // bodies... this just adds external function prototypes to the Dest
887 // function... We do this so that when we begin processing function bodies,
888 // all of the global values that may be referenced are available in our
889 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000890 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000891 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000892
Chris Lattner6cdf1972002-07-18 00:13:08 +0000893 // Update the initializers in the Dest module now that all globals that may
894 // be referenced are in Dest.
895 //
896 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
897
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000898 // Link in the function bodies that are defined in the source module into the
899 // DestModule. This consists basically of copying the function over and
900 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000901 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000902 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000903
Chris Lattner8166e6e2003-05-13 21:33:43 +0000904 // If there were any appending global variables, link them together now.
905 //
906 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
907
Chris Lattner52f7e902001-10-13 07:03:50 +0000908 return false;
909}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000910