blob: d852147a13174ba439edbef57228942ada7f85c7 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Reid Spencer78d033e2007-01-06 07:24:44 +000023#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000024#include "llvm/ValueSymbolTable.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.
John Criswell700867b2003-11-04 15:22:26 +000055//
56// Outputs:
57// DestST - The symbol table in which the new type should be placed.
58//
59// Return value:
60// true - There is an error and the types cannot yet be linked.
61// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000062//
Chris Lattnere76c57a2003-08-22 06:07:12 +000063static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
Chris Lattner371ca832008-06-16 18:11:40 +000064 TypeSymbolTable *DestST) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000065 if (DestTy == SrcTy) return false; // If already equal, noop
66
Chris Lattner4c00e532003-05-15 16:30:55 +000067 // Does the type already exist in the module?
68 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000069 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000071 } else {
72 return true; // Cannot link types... neither is opaque and not-equal
73 }
74 } else { // Type not in dest module. Add it now.
75 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000076 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77 ->refineAbstractTypeTo(SrcTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000078 }
79 return false;
80}
81
Chris Lattner43f4ba82003-08-22 19:12:55 +000082static const FunctionType *getFT(const PATypeHolder &TH) {
83 return cast<FunctionType>(TH.get());
84}
Chris Lattner9732be72003-08-22 20:16:48 +000085static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000086 return cast<StructType>(TH.get());
87}
Chris Lattnere76c57a2003-08-22 06:07:12 +000088
89// RecursiveResolveTypes - This is just like ResolveTypes, except that it
90// recurses down into derived types, merging the used types if the parent types
91// are compatible.
Chris Lattnere3092c92003-08-23 21:25:54 +000092static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
93 const PATypeHolder &SrcTy,
Chris Lattner371ca832008-06-16 18:11:40 +000094 TypeSymbolTable *DestST,
Chris Lattnere3092c92003-08-23 21:25:54 +000095 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000096 const Type *SrcTyT = SrcTy.get();
97 const Type *DestTyT = DestTy.get();
98 if (DestTyT == SrcTyT) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +000099
Chris Lattnere76c57a2003-08-22 06:07:12 +0000100 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +0000101 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
Chris Lattner371ca832008-06-16 18:11:40 +0000102 return ResolveTypes(DestTyT, SrcTyT, DestST);
Misha Brukmanf976c852005-04-21 22:55:34 +0000103
Chris Lattnere76c57a2003-08-22 06:07:12 +0000104 // Two types cannot be resolved together if they are of different primitive
105 // type. For example, we cannot resolve an int to a float.
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000106 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000107
108 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000109 switch (DestTyT->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000110 case Type::IntegerTyID: {
111 if (cast<IntegerType>(DestTyT)->getBitWidth() !=
112 cast<IntegerType>(SrcTyT)->getBitWidth())
113 return true;
114 return false;
115 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000116 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000117 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000118 cast<FunctionType>(SrcTyT)->isVarArg() ||
119 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
120 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000121 return true;
122 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000123 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
Chris Lattner371ca832008-06-16 18:11:40 +0000124 getFT(SrcTy)->getContainedType(i), DestST,
Chris Lattnere3092c92003-08-23 21:25:54 +0000125 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000126 return true;
127 return false;
128 }
129 case Type::StructTyID: {
Misha Brukmanf976c852005-04-21 22:55:34 +0000130 if (getST(DestTy)->getNumContainedTypes() !=
Chris Lattner43f4ba82003-08-22 19:12:55 +0000131 getST(SrcTy)->getNumContainedTypes()) return 1;
132 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000133 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
Chris Lattner371ca832008-06-16 18:11:40 +0000134 getST(SrcTy)->getContainedType(i), DestST,
Chris Lattnere3092c92003-08-23 21:25:54 +0000135 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000136 return true;
137 return false;
138 }
139 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000140 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
141 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000142 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000143 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000144 DestST, Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000145 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000146 case Type::PointerTyID: {
147 // If this is a pointer type, check to see if we have already seen it. If
148 // so, we are in a recursive branch. Cut off the search now. We cannot use
149 // an associative container for this search, because the type pointers (keys
150 // in the container) change whenever types get resolved...
Chris Lattnere3092c92003-08-23 21:25:54 +0000151 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
152 if (Pointers[i].first == DestTy)
153 return Pointers[i].second != SrcTy;
154
155 // Otherwise, add the current pointers to the vector to stop recursion on
156 // this pair.
157 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
158 bool Result =
159 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
160 cast<PointerType>(SrcTy.get())->getElementType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000161 DestST, Pointers);
Chris Lattnere3092c92003-08-23 21:25:54 +0000162 Pointers.pop_back();
163 return Result;
164 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000165 default: assert(0 && "Unexpected type!"); return true;
Misha Brukmanf976c852005-04-21 22:55:34 +0000166 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000167}
168
Chris Lattnere3092c92003-08-23 21:25:54 +0000169static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
170 const PATypeHolder &SrcTy,
Chris Lattner371ca832008-06-16 18:11:40 +0000171 TypeSymbolTable *DestST){
Chris Lattnere3092c92003-08-23 21:25:54 +0000172 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
Chris Lattner371ca832008-06-16 18:11:40 +0000173 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, PointerTypes);
Chris Lattnere3092c92003-08-23 21:25:54 +0000174}
175
Chris Lattnere76c57a2003-08-22 06:07:12 +0000176
Chris Lattner2c236f32001-11-03 05:18:24 +0000177// LinkTypes - Go through the symbol table of the Src module and see if any
178// types are named in the src module that are not named in the Dst module.
179// Make sure there are no type name conflicts.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000180static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000181 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
182 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000183
184 // Look for a type plane for Type's...
Reid Spencer78d033e2007-01-06 07:24:44 +0000185 TypeSymbolTable::const_iterator TI = SrcST->begin();
186 TypeSymbolTable::const_iterator TE = SrcST->end();
Reid Spencer567bc2c2004-05-25 08:52:20 +0000187 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000188
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000189 // Some types cannot be resolved immediately because they depend on other
190 // types being resolved to each other first. This contains a list of types we
191 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000192 std::vector<std::string> DelayedTypesToResolve;
193
Reid Spencer567bc2c2004-05-25 08:52:20 +0000194 for ( ; TI != TE; ++TI ) {
195 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000196 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000197
198 // Check to see if this type name is already in the dest module...
Reid Spencer78d033e2007-01-06 07:24:44 +0000199 Type *Entry = DestST->lookup(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000200
Chris Lattner371ca832008-06-16 18:11:40 +0000201 if (Entry == 0 && !Name.empty())
202 DestST->insert(Name, const_cast<Type*>(RHS));
203 else if (ResolveTypes(Entry, RHS, DestST)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000204 // They look different, save the types 'till later to resolve.
205 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000206 }
207 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000208
209 // Iteratively resolve types while we can...
210 while (!DelayedTypesToResolve.empty()) {
211 // Loop over all of the types, attempting to resolve them if possible...
212 unsigned OldSize = DelayedTypesToResolve.size();
213
Chris Lattnere76c57a2003-08-22 06:07:12 +0000214 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000215 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
216 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000217 Type *T1 = SrcST->lookup(Name);
218 Type *T2 = DestST->lookup(Name);
Chris Lattner371ca832008-06-16 18:11:40 +0000219 if (!ResolveTypes(T2, T1, DestST)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000220 // We are making progress!
221 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
222 --i;
223 }
224 }
225
226 // Did we not eliminate any types?
227 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000228 // Attempt to resolve subelements of types. This allows us to merge these
229 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000230 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
231 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000232 PATypeHolder T1(SrcST->lookup(Name));
233 PATypeHolder T2(DestST->lookup(Name));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000234
Chris Lattner371ca832008-06-16 18:11:40 +0000235 if (!RecursiveResolveTypes(T2, T1, DestST)) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000236 // We are making progress!
237 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000238
Chris Lattnere76c57a2003-08-22 06:07:12 +0000239 // Go back to the main loop, perhaps we can resolve directly by name
240 // now...
241 break;
242 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000243 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000244
245 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000246 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000247 // Remove the symbol name from the destination.
248 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000249 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000250 }
251 }
252
253
Chris Lattner2c236f32001-11-03 05:18:24 +0000254 return false;
255}
256
Chris Lattner5c2d3352003-01-30 19:53:34 +0000257static void PrintMap(const std::map<const Value*, Value*> &M) {
258 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000259 I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000260 cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000261 I->first->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000262 cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000263 I->second->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000264 cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000265 }
266}
267
268
Reid Spencer619f0242007-02-04 04:43:17 +0000269// RemapOperand - Use ValueMap to convert constants from one module to another.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000270static Value *RemapOperand(const Value *In,
Chris Lattner0033baf2004-11-16 17:12:38 +0000271 std::map<const Value*, Value*> &ValueMap) {
272 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000273 if (I != ValueMap.end())
274 return I->second;
Chris Lattner5c377c52001-10-14 23:29:15 +0000275
Reid Spencer619f0242007-02-04 04:43:17 +0000276 // Check to see if it's a constant that we are interested in transforming.
Chris Lattner620fd682006-06-01 19:14:22 +0000277 Value *Result = 0;
Chris Lattner18961502002-06-25 16:12:52 +0000278 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000279 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000280 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
Chris Lattner0033baf2004-11-16 17:12:38 +0000281 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000282
Chris Lattner18961502002-06-25 16:12:52 +0000283 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000284 std::vector<Constant*> Operands(CPA->getNumOperands());
285 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000286 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000287 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000288 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000289 std::vector<Constant*> Operands(CPS->getNumOperands());
290 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000291 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000292 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
Chris Lattnerb976e662004-10-16 18:08:06 +0000293 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000294 Result = const_cast<Constant*>(CPV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000295 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
Chris Lattnera88eb922006-01-19 23:15:58 +0000296 std::vector<Constant*> Operands(CP->getNumOperands());
297 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
298 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000299 Result = ConstantVector::get(Operands);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000300 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner27d67212006-07-14 22:21:31 +0000301 std::vector<Constant*> Ops;
302 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
303 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
304 Result = CE->getWithOperands(Ops);
Reid Spencer619f0242007-02-04 04:43:17 +0000305 } else if (isa<GlobalValue>(CPV)) {
306 assert(0 && "Unmapped global?");
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000307 } else {
308 assert(0 && "Unknown type of derived type constant value!");
309 }
Chris Lattner620fd682006-06-01 19:14:22 +0000310 } else if (isa<InlineAsm>(In)) {
311 Result = const_cast<Value*>(In);
312 }
313
Reid Spencer619f0242007-02-04 04:43:17 +0000314 // Cache the mapping in our local map structure
Chris Lattner620fd682006-06-01 19:14:22 +0000315 if (Result) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000316 ValueMap[In] = Result;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000317 return Result;
318 }
Reid Spencer8bef0372007-02-04 04:29:21 +0000319
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000320
Bill Wendlinge8156192006-12-07 01:30:32 +0000321 cerr << "LinkModules ValueMap: \n";
Chris Lattner0033baf2004-11-16 17:12:38 +0000322 PrintMap(ValueMap);
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000323
Bill Wendlinge8156192006-12-07 01:30:32 +0000324 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000325 assert(0 && "Couldn't remap value!");
326 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000327}
328
Reid Spencer8bef0372007-02-04 04:29:21 +0000329/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
330/// in the symbol table. This is good for all clients except for us. Go
331/// through the trouble to force this back.
Chris Lattnerc0036282004-08-04 07:05:54 +0000332static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
333 assert(GV->getName() != Name && "Can't force rename to self");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000334 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
Chris Lattnerc0036282004-08-04 07:05:54 +0000335
336 // If there is a conflict, rename the conflict.
Chris Lattner33f29492007-02-11 00:39:38 +0000337 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000338 assert(ConflictGV->hasInternalLinkage() &&
339 "Not conflicting with a static global, should link instead!");
Chris Lattner33f29492007-02-11 00:39:38 +0000340 GV->takeName(ConflictGV);
341 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Reid Spenceref9b9a72007-02-05 20:47:22 +0000342 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000343 } else {
344 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000345 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000346}
Reid Spencer8bef0372007-02-04 04:29:21 +0000347
Reid Spenceref9b9a72007-02-05 20:47:22 +0000348/// CopyGVAttributes - copy additional attributes (those not needed to construct
349/// a GlobalValue) from the SrcGV to the DestGV.
350static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000351 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
352 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
353 DestGV->copyAttributesFrom(SrcGV);
354 DestGV->setAlignment(Alignment);
Chris Lattnerc0036282004-08-04 07:05:54 +0000355}
356
Chris Lattneraee38ea2004-12-03 22:18:41 +0000357/// GetLinkageResult - This analyzes the two global values and determines what
358/// the result will look like in the destination module. In particular, it
359/// computes the resultant linkage type, computes whether the global in the
360/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000361/// one), and computes whether this linkage is an error or not. It also performs
362/// visibility checks: we cannot link together two symbols with different
363/// visibilities.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000364static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Chris Lattneraee38ea2004-12-03 22:18:41 +0000365 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
366 std::string *Err) {
367 assert((!Dest || !Src->hasInternalLinkage()) &&
368 "If Src has internal linkage, Dest shouldn't be set!");
369 if (!Dest) {
370 // Linking something to nothing.
371 LinkFromSrc = true;
372 LT = Src->getLinkage();
Reid Spencer5cbf9852007-01-30 20:08:39 +0000373 } else if (Src->isDeclaration()) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000374 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000375 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000376 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000377 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000378 if (Dest->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000379 LinkFromSrc = true;
380 LT = Src->getLinkage();
381 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000382 } else if (Dest->hasExternalWeakLinkage()) {
383 //If the Dest is weak, use the source linkage
384 LinkFromSrc = true;
385 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000386 } else {
387 LinkFromSrc = false;
388 LT = Dest->getLinkage();
389 }
Reid Spencer5cbf9852007-01-30 20:08:39 +0000390 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000391 // If Dest is external but Src is not:
392 LinkFromSrc = true;
393 LT = Src->getLinkage();
394 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
395 if (Src->getLinkage() != Dest->getLinkage())
396 return Error(Err, "Linking globals named '" + Src->getName() +
397 "': can only link appending global with another appending global!");
398 LinkFromSrc = true; // Special cased.
399 LT = Src->getLinkage();
Dale Johannesenaafce772008-05-14 20:12:51 +0000400 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
401 Src->hasCommonLinkage()) {
402 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
403 // or DLL* linkage.
404 if ((Dest->hasLinkOnceLinkage() &&
405 (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000406 Dest->hasExternalWeakLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000407 LinkFromSrc = true;
408 LT = Src->getLinkage();
409 } else {
410 LinkFromSrc = false;
411 LT = Dest->getLinkage();
412 }
Dale Johannesenaafce772008-05-14 20:12:51 +0000413 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
414 Dest->hasCommonLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000415 // At this point we know that Src has External* or DLL* linkage.
416 if (Src->hasExternalWeakLinkage()) {
417 LinkFromSrc = false;
418 LT = Dest->getLinkage();
419 } else {
420 LinkFromSrc = true;
421 LT = GlobalValue::ExternalLinkage;
422 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000423 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000424 assert((Dest->hasExternalLinkage() ||
425 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000426 Dest->hasDLLExportLinkage() ||
427 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000428 (Src->hasExternalLinkage() ||
429 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000430 Src->hasDLLExportLinkage() ||
431 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000432 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000433 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000434 "': symbol multiply defined!");
435 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000436
437 // Check visibility
438 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattner97f8b092007-08-19 22:22:54 +0000439 if (!Src->isDeclaration() && !Dest->isDeclaration())
440 return Error(Err, "Linking globals named '" + Src->getName() +
441 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000442 return false;
443}
Chris Lattner5c377c52001-10-14 23:29:15 +0000444
445// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000446// them into the dest module.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000447static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000448 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000449 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000450 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000451 // Loop over all of the globals in the src module, mapping them over as we go
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000452 for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
Chris Lattner11273152006-06-16 01:24:04 +0000453 I != E; ++I) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000454 const GlobalVariable *SGV = I;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000455 GlobalValue *DGV = 0;
456
457 // Check to see if may have to link the global with the global
Reid Spenceref9b9a72007-02-05 20:47:22 +0000458 if (SGV->hasName() && !SGV->hasInternalLinkage()) {
459 DGV = Dest->getGlobalVariable(SGV->getName());
460 if (DGV && DGV->getType() != SGV->getType())
461 // If types don't agree due to opaque types, try to resolve them.
462 RecursiveResolveTypes(SGV->getType(), DGV->getType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000463 &Dest->getTypeSymbolTable());
Reid Spenceref9b9a72007-02-05 20:47:22 +0000464 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000465
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000466 // Check to see if may have to link the global with the alias
Anton Korobeynikovaeb09962008-03-10 22:35:31 +0000467 if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000468 DGV = Dest->getNamedAlias(SGV->getName());
469 if (DGV && DGV->getType() != SGV->getType())
470 // If types don't agree due to opaque types, try to resolve them.
471 RecursiveResolveTypes(SGV->getType(), DGV->getType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000472 &Dest->getTypeSymbolTable());
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000473 }
474
Chris Lattneraee38ea2004-12-03 22:18:41 +0000475 if (DGV && DGV->hasInternalLinkage())
476 DGV = 0;
477
Dan Gohmanc3183292007-10-08 15:13:30 +0000478 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
479 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000480 "Global must either be external or have an initializer!");
481
Chris Lattnerb324bd72006-11-09 05:18:12 +0000482 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
483 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000484 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
485 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000486
Chris Lattneraee38ea2004-12-03 22:18:41 +0000487 if (!DGV) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000488 // No linking to be performed, simply create an identical version of the
489 // symbol over in the dest module... the initializer will be filled in
490 // later by LinkGlobalInits...
Chris Lattner2719bac2003-04-21 21:15:04 +0000491 GlobalVariable *NewDGV =
492 new GlobalVariable(SGV->getType()->getElementType(),
493 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikove20c8142008-03-07 18:32:18 +0000494 SGV->getName(), Dest);
Reid Spencer471feac2007-02-04 04:30:33 +0000495 // Propagate alignment, visibility and section info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000496 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000497
Chris Lattner2719bac2003-04-21 21:15:04 +0000498 // If the LLVM runtime renamed the global, but it is an externally visible
499 // symbol, DGV must be an existing global with internal linkage. Rename
500 // it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000501 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
502 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000503
504 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000505 ValueMap[SGV] = NewDGV;
506
Chris Lattner8166e6e2003-05-13 21:33:43 +0000507 if (SGV->hasAppendingLinkage())
508 // Keep track that this is an appending variable...
509 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattneraee38ea2004-12-03 22:18:41 +0000510 } else if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000511 // No linking is performed yet. Just insert a new copy of the global, and
512 // keep track of the fact that it is an appending variable in the
513 // AppendingVars map. The name is cleared out so that no linkage is
514 // performed.
515 GlobalVariable *NewDGV =
516 new GlobalVariable(SGV->getType()->getElementType(),
517 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikove20c8142008-03-07 18:32:18 +0000518 "", Dest);
Chris Lattner8166e6e2003-05-13 21:33:43 +0000519
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000520 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000521 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000522 // Propagate alignment, section and visibility info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000523 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000524
Chris Lattner8166e6e2003-05-13 21:33:43 +0000525 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000526 ValueMap[SGV] = NewDGV;
Chris Lattner8166e6e2003-05-13 21:33:43 +0000527
528 // Keep track that this is an appending variable...
529 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000530 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
531 // SGV is global, but DGV is alias. The only valid mapping is when SGV is
532 // external declaration, which is effectively a no-op. Also make sure
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000533 // linkage calculation was correct.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000534 if (SGV->isDeclaration() && !LinkFromSrc) {
535 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000536 ValueMap[SGV] = DGA;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000537 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000538 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
539 "': symbol multiple defined");
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000540 } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000541 // Otherwise, perform the global-global mapping as instructed by
542 // GetLinkageResult.
Chris Lattneraee38ea2004-12-03 22:18:41 +0000543 if (LinkFromSrc) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000544 // Propagate alignment, section, and visibility info.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000545 CopyGVAttributes(DGVar, SGV);
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000546
547 // If the types don't match, and if we are to link from the source, nuke
548 // DGV and create a new one of the appropriate type.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000549 if (SGV->getType() != DGVar->getType()) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000550 GlobalVariable *NewDGV =
551 new GlobalVariable(SGV->getType()->getElementType(),
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000552 DGVar->isConstant(), DGVar->getLinkage(),
553 /*init*/0, DGVar->getName(), Dest);
554 CopyGVAttributes(NewDGV, DGVar);
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000555 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000556 DGVar->getType()));
557 // DGVar will conflict with NewDGV because they both had the same
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000558 // name. We must erase this now so ForceRenaming doesn't assert
559 // because DGV might not have internal linkage.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000560 DGVar->eraseFromParent();
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000561
562 // If the symbol table renamed the global, but it is an externally
563 // visible symbol, DGV must be an existing global with internal
564 // linkage. Rename it.
565 if (NewDGV->getName() != SGV->getName() &&
566 !NewDGV->hasInternalLinkage())
567 ForceRenaming(NewDGV, SGV->getName());
568
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000569 DGVar = NewDGV;
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000570 }
571
Chris Lattneraee38ea2004-12-03 22:18:41 +0000572 // Inherit const as appropriate
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000573 DGVar->setConstant(SGV->isConstant());
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000574
575 // Set initializer to zero, so we can link the stuff later
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000576 DGVar->setInitializer(0);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000577 } else {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000578 // Special case for const propagation
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000579 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
580 DGVar->setConstant(true);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000581 }
582
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000583 // Set calculated linkage
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000584 DGVar->setLinkage(NewLinkage);
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000585
586 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000587 ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000588 }
589 }
590 return false;
591}
592
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000593static GlobalValue::LinkageTypes
594CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
595 if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
596 return GlobalValue::ExternalLinkage;
597 else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
598 return GlobalValue::WeakLinkage;
599 else {
600 assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
601 "Unexpected linkage type");
602 return GlobalValue::InternalLinkage;
603 }
604}
605
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000606// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000607// dest module. We're assuming, that all functions/global variables were already
608// linked in.
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000609static bool LinkAlias(Module *Dest, const Module *Src,
610 std::map<const Value*, Value*> &ValueMap,
611 std::string *Err) {
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000612 // Loop over all alias in the src module
613 for (Module::const_alias_iterator I = Src->alias_begin(),
614 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000615 const GlobalAlias *SGA = I;
616 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
617 GlobalAlias *NewGA = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000618
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000619 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000620 // of SAliasee in Dest.
Ted Kremenek58d5e052008-03-09 18:32:50 +0000621 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
622 assert(VMI != ValueMap.end() && "Aliasee not linked");
623 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000624 GlobalValue* DGV = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000625
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000626 // Try to find something 'similar' to SGA in destination module.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000627 if (!DGV && !SGA->hasInternalLinkage()) {
628 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000629
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000630 // If types don't agree due to opaque types, try to resolve them.
631 if (DGV && DGV->getType() != SGA->getType())
632 if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000633 &Dest->getTypeSymbolTable()))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000634 return Error(Err, "Alias Collision on '" + SGA->getName()+
635 "': aliases have different types");
636 }
637
638 if (!DGV && !SGA->hasInternalLinkage()) {
639 DGV = Dest->getGlobalVariable(SGA->getName());
640
641 // If types don't agree due to opaque types, try to resolve them.
642 if (DGV && DGV->getType() != SGA->getType())
643 if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000644 &Dest->getTypeSymbolTable()))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000645 return Error(Err, "Alias Collision on '" + SGA->getName()+
646 "': aliases have different types");
647 }
648
649 if (!DGV && !SGA->hasInternalLinkage()) {
650 DGV = Dest->getFunction(SGA->getName());
651
652 // If types don't agree due to opaque types, try to resolve them.
653 if (DGV && DGV->getType() != SGA->getType())
654 if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000655 &Dest->getTypeSymbolTable()))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000656 return Error(Err, "Alias Collision on '" + SGA->getName()+
657 "': aliases have different types");
658 }
659
660 // No linking to be performed on internal stuff.
661 if (DGV && DGV->hasInternalLinkage())
662 DGV = NULL;
663
664 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
665 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000666 // globals are already linked we just need query ValueMap to find the
667 // mapping.
668 if (DAliasee == DGA->getAliasedGlobal()) {
669 // This is just two copies of the same alias. Propagate linkage, if
670 // necessary.
671 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
672
673 NewGA = DGA;
674 // Proceed to 'common' steps
675 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000676 return Error(Err, "Alias Collision on '" + SGA->getName()+
677 "': aliases have different aliasees");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000678 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000679 // The only allowed way is to link alias with external declaration.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000680 if (DGVar->isDeclaration()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000681 // But only if aliasee is global too...
682 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000683 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
684 "': aliasee is not global variable");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000685
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000686 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
687 SGA->getName(), DAliasee, Dest);
688 CopyGVAttributes(NewGA, SGA);
689
690 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000691 if (SGA->getType() != DGVar->getType())
692 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
693 DGVar->getType()));
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000694 else
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000695 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000696
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000697 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000698 // name. We must erase this now so ForceRenaming doesn't assert
699 // because DGV might not have internal linkage.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000700 DGVar->eraseFromParent();
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000701
702 // Proceed to 'common' steps
703 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000704 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
705 "': symbol multiple defined");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000706 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000707 // The only allowed way is to link alias with external declaration.
708 if (DF->isDeclaration()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000709 // But only if aliasee is function too...
710 if (!isa<Function>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000711 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
712 "': aliasee is not function");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000713
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000714 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
715 SGA->getName(), DAliasee, Dest);
716 CopyGVAttributes(NewGA, SGA);
717
718 // Any uses of DF need to change to NewGA, with cast, if needed.
719 if (SGA->getType() != DF->getType())
720 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
721 DF->getType()));
722 else
723 DF->replaceAllUsesWith(NewGA);
724
725 // DF will conflict with NewGA because they both had the same
726 // name. We must erase this now so ForceRenaming doesn't assert
727 // because DF might not have internal linkage.
728 DF->eraseFromParent();
729
730 // Proceed to 'common' steps
731 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000732 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
733 "': symbol multiple defined");
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000734 } else {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000735 // No linking to be performed, simply create an identical version of the
736 // alias over in the dest module...
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000737
738 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
739 SGA->getName(), DAliasee, Dest);
740 CopyGVAttributes(NewGA, SGA);
741
742 // Proceed to 'common' steps
743 }
744
745 assert(NewGA && "No alias was created in destination module!");
746
Anton Korobeynikovb8cdaf72008-03-10 22:36:35 +0000747 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000748 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000749 if (NewGA->getName() != SGA->getName() &&
750 !NewGA->hasInternalLinkage())
751 ForceRenaming(NewGA, SGA->getName());
752
753 // Remember this mapping so uses in the source module get remapped
754 // later by RemapOperand.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000755 ValueMap[SGA] = NewGA;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000756 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000757
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000758 return false;
759}
760
Chris Lattner5c377c52001-10-14 23:29:15 +0000761
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000762// LinkGlobalInits - Update the initializers in the Dest module now that all
763// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000764static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000765 std::map<const Value*, Value*> &ValueMap,
766 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000767
768 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000769 for (Module::const_global_iterator I = Src->global_begin(),
770 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000771 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000772
773 if (SGV->hasInitializer()) { // Only process initialized GV's
774 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000775 Constant *SInit =
Chris Lattner0033baf2004-11-16 17:12:38 +0000776 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000777
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000778 GlobalVariable *DGV =
779 cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000780 if (DGV->hasInitializer()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000781 if (SGV->hasExternalLinkage()) {
782 if (DGV->getInitializer() != SInit)
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000783 return Error(Err, "Global Variable Collision on '" + SGV->getName() +
784 "': global variables have different initializers");
Dale Johannesenaafce772008-05-14 20:12:51 +0000785 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
786 DGV->hasCommonLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000787 // Nothing is required, mapped values will take the new global
788 // automatically.
Dale Johannesenaafce772008-05-14 20:12:51 +0000789 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
790 SGV->hasCommonLinkage()) {
Chris Lattner57cb9882004-02-17 21:56:04 +0000791 // Nothing is required, mapped values will take the new global
792 // automatically.
Chris Lattner4ad02e72003-04-16 20:28:45 +0000793 } else if (DGV->hasAppendingLinkage()) {
794 assert(0 && "Appending linkage unimplemented!");
795 } else {
796 assert(0 && "Unknown linkage!");
797 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000798 } else {
799 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000800 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000801 }
802 }
803 }
804 return false;
805}
Chris Lattner5c377c52001-10-14 23:29:15 +0000806
Chris Lattner79df7c02002-03-26 18:01:55 +0000807// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000808// without doing function bodies... this just adds external function prototypes
809// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000810//
Chris Lattner79df7c02002-03-26 18:01:55 +0000811static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000812 std::map<const Value*, Value*> &ValueMap,
813 std::string *Err) {
Reid Spencer619f0242007-02-04 04:43:17 +0000814 // Loop over all of the functions in the src module, mapping them over
Chris Lattner5c377c52001-10-14 23:29:15 +0000815 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000816 const Function *SF = I; // SrcFunction
Chris Lattner82468492008-06-09 07:36:11 +0000817
Chris Lattner4ad02e72003-04-16 20:28:45 +0000818 Function *DF = 0;
Chris Lattner82468492008-06-09 07:36:11 +0000819
820 // If this function is internal or has no name, it doesn't participate in
821 // linkage.
Reid Spencer8bef0372007-02-04 04:29:21 +0000822 if (SF->hasName() && !SF->hasInternalLinkage()) {
823 // Check to see if may have to link the function.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000824 DF = Dest->getFunction(SF->getName());
Chris Lattner82468492008-06-09 07:36:11 +0000825 if (DF && DF->hasInternalLinkage())
826 DF = 0;
Reid Spencer8bef0372007-02-04 04:29:21 +0000827 }
Chris Lattnerbc3d1c72008-06-09 07:25:28 +0000828
Chris Lattner82468492008-06-09 07:36:11 +0000829 // If there is no linkage to be performed, just bring over SF without
830 // modifying it.
831 if (DF == 0) {
832 // Function does not already exist, simply insert an function signature
833 // identical to SF into the dest module.
834 Function *NewDF = Function::Create(SF->getFunctionType(),
835 SF->getLinkage(),
836 SF->getName(), Dest);
837 CopyGVAttributes(NewDF, SF);
838
839 // If the LLVM runtime renamed the function, but it is an externally
840 // visible symbol, DF must be an existing function with internal linkage.
841 // Rename it.
842 if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
843 ForceRenaming(NewDF, SF->getName());
844
845 // ... and remember this mapping...
846 ValueMap[SF] = NewDF;
847 continue;
848 }
849
850
851 // If types don't agree because of opaque, try to resolve them.
852 if (SF->getType() != DF->getType())
853 RecursiveResolveTypes(SF->getType(), DF->getType(),
Chris Lattner371ca832008-06-16 18:11:40 +0000854 &Dest->getTypeSymbolTable());
Chris Lattner82468492008-06-09 07:36:11 +0000855
856 // Check visibility, merging if a definition overrides a prototype.
857 if (SF->getVisibility() != DF->getVisibility()) {
Chris Lattner97f8b092007-08-19 22:22:54 +0000858 // If one is a prototype, ignore its visibility. Prototypes are always
859 // overridden by the definition.
860 if (!SF->isDeclaration() && !DF->isDeclaration())
861 return Error(Err, "Linking functions named '" + SF->getName() +
862 "': symbols have different visibilities!");
Chris Lattnerbc3d1c72008-06-09 07:25:28 +0000863
864 // Otherwise, replace the visibility of DF if DF is a prototype.
865 if (DF->isDeclaration())
866 DF->setVisibility(SF->getVisibility());
Chris Lattner97f8b092007-08-19 22:22:54 +0000867 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000868
Chris Lattner82468492008-06-09 07:36:11 +0000869 if (DF->getType() != SF->getType()) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000870 if (DF->isDeclaration() && !SF->isDeclaration()) {
871 // We have a definition of the same name but different type in the
872 // source module. Copy the prototype to the destination and replace
873 // uses of the destination's prototype with the new prototype.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000874 Function *NewDF = Function::Create(SF->getFunctionType(),
875 SF->getLinkage(),
Gabor Greif051a9502008-04-06 20:25:17 +0000876 SF->getName(), Dest);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000877 CopyGVAttributes(NewDF, SF);
Chris Lattner5c377c52001-10-14 23:29:15 +0000878
Reid Spenceref9b9a72007-02-05 20:47:22 +0000879 // Any uses of DF need to change to NewDF, with cast
880 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
881
882 // DF will conflict with NewDF because they both had the same. We must
883 // erase this now so ForceRenaming doesn't assert because DF might
884 // not have internal linkage.
885 DF->eraseFromParent();
886
887 // If the symbol table renamed the function, but it is an externally
888 // visible symbol, DF must be an existing function with internal
889 // linkage. Rename it.
890 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
891 ForceRenaming(NewDF, SF->getName());
892
893 // Remember this mapping so uses in the source module get remapped
894 // later by RemapOperand.
895 ValueMap[SF] = NewDF;
896 } else if (SF->isDeclaration()) {
897 // We have two functions of the same name but different type and the
898 // source is a declaration while the destination is not. Any use of
899 // the source must be mapped to the destination, with a cast.
900 ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType());
901 } else {
902 // We have two functions of the same name but different types and they
903 // are both definitions. This is an error.
904 return Error(Err, "Function '" + DF->getName() + "' defined as both '" +
905 ToStr(SF->getFunctionType(), Src) + "' and '" +
906 ToStr(DF->getFunctionType(), Dest) + "'");
907 }
Chris Lattner82468492008-06-09 07:36:11 +0000908 continue;
909 }
910
911 if (SF->isDeclaration()) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000912 // If SF is a declaration or if both SF & DF are declarations, just link
913 // the declarations, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000914 if (SF->hasDLLImportLinkage()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000915 if (DF->isDeclaration()) {
Chris Lattner822143e2008-06-09 07:47:34 +0000916 ValueMap[SF] = DF;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000917 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000918 }
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000919 } else {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000920 ValueMap[SF] = DF;
Chris Lattner822143e2008-06-09 07:47:34 +0000921 }
922 continue;
923 }
924
925 // If DF is external but SF is not, link the external functions, update
926 // linkage qualifiers.
927 if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000928 ValueMap.insert(std::make_pair(SF, DF));
929 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000930 continue;
931 }
932
933 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
934 if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
935 SF->hasCommonLinkage()) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000936 ValueMap[SF] = DF;
Chris Lattner72ac148d2003-10-16 18:29:00 +0000937
Chris Lattner35956552003-10-27 16:39:39 +0000938 // Linkonce+Weak = Weak
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000939 // *+External Weak = *
Dale Johannesenaafce772008-05-14 20:12:51 +0000940 if ((DF->hasLinkOnceLinkage() &&
941 (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000942 DF->hasExternalWeakLinkage())
Chris Lattner35956552003-10-27 16:39:39 +0000943 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000944 continue;
945 }
946
947 if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
948 DF->hasCommonLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000949 // At this point we know that SF has LinkOnce or External* linkage.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000950 ValueMap[SF] = DF;
Chris Lattner822143e2008-06-09 07:47:34 +0000951
952 // If the source function has stronger linkage than the destination,
953 // its body and linkage should override ours.
954 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
955 // Don't inherit linkonce & external weak linkage.
Chris Lattner72ac148d2003-10-16 18:29:00 +0000956 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000957 DF->deleteBody();
958 }
959 continue;
960 }
961
962 if (SF->getLinkage() != DF->getLinkage())
963 return Error(Err, "Functions named '" + SF->getName() +
964 "' have different linkage specifiers!");
965
966 // The function is defined identically in both modules!
967 if (SF->hasExternalLinkage())
Misha Brukmanf976c852005-04-21 22:55:34 +0000968 return Error(Err, "Function '" +
969 ToStr(SF->getFunctionType(), Src) + "':\"" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000970 SF->getName() + "\" - Function is already defined!");
Chris Lattner822143e2008-06-09 07:47:34 +0000971 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000972 }
973 return false;
974}
975
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000976// LinkFunctionBody - Copy the source function over into the dest function and
977// fix up references to values. At this point we know that Dest is an external
978// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000979static bool LinkFunctionBody(Function *Dest, Function *Src,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000980 std::map<const Value*, Value*> &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000981 std::string *Err) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000982 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000983
Chris Lattner0033baf2004-11-16 17:12:38 +0000984 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +0000985 Function::arg_iterator DI = Dest->arg_begin();
986 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000987 I != E; ++I, ++DI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000988 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000989
990 // Add a mapping to our local map
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000991 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000992 }
993
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000994 // Splice the body of the source function into the dest function.
995 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +0000996
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000997 // At this point, all of the instructions and values of the function are now
998 // copied over. The only problem is that they are still referencing values in
999 // the Source function as operands. Loop through all of the operands of the
1000 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +00001001 //
Chris Lattner18961502002-06-25 16:12:52 +00001002 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1003 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1004 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +00001005 OI != OE; ++OI)
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001006 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Reid Spenceref9b9a72007-02-05 20:47:22 +00001007 *OI = RemapOperand(*OI, ValueMap);
Chris Lattner0033baf2004-11-16 17:12:38 +00001008
1009 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +00001010 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1011 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +00001012 ValueMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +00001013
1014 return false;
1015}
1016
1017
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001018// LinkFunctionBodies - Link in the function bodies that are defined in the
1019// source module into the DestModule. This consists basically of copying the
1020// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001021static bool LinkFunctionBodies(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001022 std::map<const Value*, Value*> &ValueMap,
1023 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +00001024
Reid Spencer8bef0372007-02-04 04:29:21 +00001025 // Loop over all of the functions in the src module, mapping them over as we
1026 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001027 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer619f0242007-02-04 04:43:17 +00001028 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattner18961502002-06-25 16:12:52 +00001029 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +00001030
Chris Lattner18961502002-06-25 16:12:52 +00001031 // DF not external SF external?
Reid Spenceref9b9a72007-02-05 20:47:22 +00001032 if (DF->isDeclaration())
Chris Lattner35956552003-10-27 16:39:39 +00001033 // Only provide the function body if there isn't one already.
1034 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1035 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +00001036 }
Chris Lattner5c377c52001-10-14 23:29:15 +00001037 }
1038 return false;
1039}
1040
Chris Lattner8166e6e2003-05-13 21:33:43 +00001041// LinkAppendingVars - If there were any appending global variables, link them
1042// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001043static bool LinkAppendingVars(Module *M,
1044 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1045 std::string *ErrorMsg) {
1046 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +00001047
Chris Lattner8166e6e2003-05-13 21:33:43 +00001048 // Loop over the multimap of appending vars, processing any variables with the
1049 // same name, forming a new appending global variable with both of the
1050 // initializers merged together, then rewrite references to the old variables
1051 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001052 std::vector<Constant*> Inits;
1053 while (AppendingVars.size() > 1) {
1054 // Get the first two elements in the map...
1055 std::multimap<std::string,
1056 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1057
1058 // If the first two elements are for different names, there is no pair...
1059 // Otherwise there is a pair, so link them together...
1060 if (First->first == Second->first) {
1061 GlobalVariable *G1 = First->second, *G2 = Second->second;
1062 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1063 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +00001064
Chris Lattner8166e6e2003-05-13 21:33:43 +00001065 // Check to see that they two arrays agree on type...
1066 if (T1->getElementType() != T2->getElementType())
1067 return Error(ErrorMsg,
1068 "Appending variables with different element types need to be linked!");
1069 if (G1->isConstant() != G2->isConstant())
1070 return Error(ErrorMsg,
1071 "Appending variables linked with different const'ness!");
1072
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001073 if (G1->getAlignment() != G2->getAlignment())
1074 return Error(ErrorMsg,
1075 "Appending variables with different alignment need to be linked!");
1076
1077 if (G1->getVisibility() != G2->getVisibility())
1078 return Error(ErrorMsg,
1079 "Appending variables with different visibility need to be linked!");
1080
1081 if (G1->getSection() != G2->getSection())
1082 return Error(ErrorMsg,
1083 "Appending variables with different section name need to be linked!");
1084
Chris Lattner8166e6e2003-05-13 21:33:43 +00001085 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1086 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1087
Chris Lattnered74a4e2005-12-06 17:30:58 +00001088 G1->setName(""); // Clear G1's name in case of a conflict!
1089
Chris Lattner8166e6e2003-05-13 21:33:43 +00001090 // Create the new global variable...
1091 GlobalVariable *NG =
1092 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001093 /*init*/0, First->first, M, G1->isThreadLocal());
Chris Lattner8166e6e2003-05-13 21:33:43 +00001094
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001095 // Propagate alignment, visibility and section info.
1096 CopyGVAttributes(NG, G1);
1097
Chris Lattner8166e6e2003-05-13 21:33:43 +00001098 // Merge the initializer...
1099 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +00001100 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1101 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001102 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001103 } else {
1104 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1105 Constant *CV = Constant::getNullValue(T1->getElementType());
1106 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1107 Inits.push_back(CV);
1108 }
1109 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1110 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001111 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001112 } else {
1113 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1114 Constant *CV = Constant::getNullValue(T2->getElementType());
1115 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1116 Inits.push_back(CV);
1117 }
Chris Lattner8166e6e2003-05-13 21:33:43 +00001118 NG->setInitializer(ConstantArray::get(NewType, Inits));
1119 Inits.clear();
1120
1121 // Replace any uses of the two global variables with uses of the new
1122 // global...
1123
1124 // FIXME: This should rewrite simple/straight-forward uses such as
1125 // getelementptr instructions to not use the Cast!
Reid Spencer4da49122006-12-12 05:05:00 +00001126 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1127 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001128
1129 // Remove the two globals from the module now...
1130 M->getGlobalList().erase(G1);
1131 M->getGlobalList().erase(G2);
1132
1133 // Put the new global into the AppendingVars map so that we can handle
1134 // linking of more than two vars...
1135 Second->second = NG;
1136 }
1137 AppendingVars.erase(First);
1138 }
1139
1140 return false;
1141}
Chris Lattner52f7e902001-10-13 07:03:50 +00001142
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001143static bool ResolveAliases(Module *Dest) {
1144 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov52419572008-03-11 22:51:09 +00001145 I != E; ++I)
1146 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1147 if (!GV->isDeclaration())
1148 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001149
1150 return false;
1151}
Chris Lattner52f7e902001-10-13 07:03:50 +00001152
1153// LinkModules - This function links two modules together, with the resulting
1154// left module modified to be the composite of the two input modules. If an
1155// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001156// the problem. Upon failure, the Dest module could be in a modified state, and
1157// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +00001158bool
Reid Spencer0ba9e212004-12-13 03:00:16 +00001159Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +00001160 assert(Dest != 0 && "Invalid Destination module");
1161 assert(Src != 0 && "Invalid Source Module");
1162
Chris Lattnerc36357c2007-01-29 00:21:34 +00001163 if (Dest->getDataLayout().empty()) {
1164 if (!Src->getDataLayout().empty()) {
Chris Lattnerec9bfdc2007-01-29 02:18:13 +00001165 Dest->setDataLayout(Src->getDataLayout());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001166 } else {
1167 std::string DataLayout;
Reid Spencer26f23852007-01-26 08:11:39 +00001168
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001169 if (Dest->getEndianness() == Module::AnyEndianness) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001170 if (Src->getEndianness() == Module::BigEndian)
1171 DataLayout.append("E");
1172 else if (Src->getEndianness() == Module::LittleEndian)
1173 DataLayout.append("e");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001174 }
1175
1176 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001177 if (Src->getPointerSize() == Module::Pointer64)
1178 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1179 else if (Src->getPointerSize() == Module::Pointer32)
1180 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001181 }
Chris Lattnerc36357c2007-01-29 00:21:34 +00001182 Dest->setDataLayout(DataLayout);
1183 }
1184 }
1185
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001186 // Copy the target triple from the source to dest if the dest's is empty.
Chris Lattnerc36357c2007-01-29 00:21:34 +00001187 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
Chris Lattner152f19a2004-12-10 20:26:15 +00001188 Dest->setTargetTriple(Src->getTargetTriple());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001189
1190 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1191 Src->getDataLayout() != Dest->getDataLayout())
Reid Spencer26f23852007-01-26 08:11:39 +00001192 cerr << "WARNING: Linking two modules of different data layouts!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +00001193 if (!Src->getTargetTriple().empty() &&
1194 Dest->getTargetTriple() != Src->getTargetTriple())
Bill Wendlinge8156192006-12-07 01:30:32 +00001195 cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001196
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001197 // Append the module inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001198 if (!Src->getModuleInlineAsm().empty()) {
1199 if (Dest->getModuleInlineAsm().empty())
1200 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001201 else
Chris Lattner66316012006-01-24 04:14:29 +00001202 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1203 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001204 }
1205
Reid Spencer719012d2004-11-25 09:29:44 +00001206 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +00001207 // from the source module. There's no opportunity for duplicates here as the
1208 // Module ensures that duplicate insertions are discarded.
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001209 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1210 SI != SE; ++SI)
Reid Spencer57a0efa2004-09-11 04:25:17 +00001211 Dest->addLibrary(*SI);
Reid Spencer57a0efa2004-09-11 04:25:17 +00001212
Chris Lattner2c236f32001-11-03 05:18:24 +00001213 // LinkTypes - Go through the symbol table of the Src module and see if any
1214 // types are named in the src module that are not named in the Dst module.
1215 // Make sure there are no type name conflicts.
Reid Spencer619f0242007-02-04 04:43:17 +00001216 if (LinkTypes(Dest, Src, ErrorMsg))
1217 return true;
Chris Lattner2c236f32001-11-03 05:18:24 +00001218
Chris Lattner5c377c52001-10-14 23:29:15 +00001219 // ValueMap - Mapping of values from what they used to be in Src, to what they
1220 // are now in Dest.
Chris Lattner5c2d3352003-01-30 19:53:34 +00001221 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +00001222
Chris Lattner8166e6e2003-05-13 21:33:43 +00001223 // AppendingVars - Keep track of global variables in the destination module
1224 // with appending linkage. After the module is linked together, they are
1225 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001226 std::multimap<std::string, GlobalVariable *> AppendingVars;
Chris Lattner11273152006-06-16 01:24:04 +00001227 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1228 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +00001229 // Add all of the appending globals already in the Dest module to
1230 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +00001231 if (I->hasAppendingLinkage())
1232 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner5a837de2004-08-04 07:44:58 +00001233 }
1234
Chris Lattner8166e6e2003-05-13 21:33:43 +00001235 // Insert all of the globals in src into the Dest module... without linking
1236 // initializers (which could refer to functions not yet mapped over).
Reid Spenceref9b9a72007-02-05 20:47:22 +00001237 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001238 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001239
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001240 // Link the functions together between the two modules, without doing function
1241 // bodies... this just adds external function prototypes to the Dest
1242 // function... We do this so that when we begin processing function bodies,
1243 // all of the global values that may be referenced are available in our
1244 // ValueMap.
Reid Spenceref9b9a72007-02-05 20:47:22 +00001245 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001246 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001247
Anton Korobeynikov4fb28732008-03-05 15:27:21 +00001248 // If there were any alias, link them now. We really need to do this now,
1249 // because all of the aliases that may be referenced need to be available in
1250 // ValueMap
1251 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1252
Chris Lattner6cdf1972002-07-18 00:13:08 +00001253 // Update the initializers in the Dest module now that all globals that may
1254 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +00001255 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1256
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001257 // Link in the function bodies that are defined in the source module into the
1258 // DestModule. This consists basically of copying the function over and
1259 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +00001260 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +00001261
Chris Lattner8166e6e2003-05-13 21:33:43 +00001262 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001263 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1264
Anton Korobeynikov3db91912008-03-05 23:08:47 +00001265 // Resolve all uses of aliases with aliasees
1266 if (ResolveAliases(Dest)) return true;
1267
Reid Spencer57a0efa2004-09-11 04:25:17 +00001268 // If the source library's module id is in the dependent library list of the
1269 // destination library, remove it since that module is now linked in.
1270 sys::Path modId;
Reid Spencerdd04df02005-07-07 23:21:43 +00001271 modId.set(Src->getModuleIdentifier());
Reid Spencer07adb282004-11-05 22:15:36 +00001272 if (!modId.isEmpty())
1273 Dest->removeLibrary(modId.getBasename());
Reid Spencer57a0efa2004-09-11 04:25:17 +00001274
Chris Lattner52f7e902001-10-13 07:03:50 +00001275 return false;
1276}
Vikram S. Adve9466f512001-10-28 21:38:02 +00001277
Reid Spencer567bc2c2004-05-25 08:52:20 +00001278// vim: sw=2