1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM module linker.
12 // Specifically, this:
13 // * Merges global variables between the two modules
14 // * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15 // * Merges functions between two modules
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Linker.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/System/Path.h"
31 // Error - Simple wrapper function to conditionally assign to E and return true.
32 // This just makes error return conditions a little bit simpler...
33 static inline bool Error(std::string
*E
, const std::string
&Message
) {
38 // ToStr - Simple wrapper function to convert a type to a string.
39 static std::string
ToStr(const Type
*Ty
, const Module
*M
) {
40 std::ostringstream OS
;
41 WriteTypeSymbolic(OS
, Ty
, M
);
46 // Function: ResolveTypes()
49 // Attempt to link the two specified types together.
52 // DestTy - The type to which we wish to resolve.
53 // SrcTy - The original type which we want to resolve.
54 // Name - The name of the type.
57 // DestST - The symbol table in which the new type should be placed.
60 // true - There is an error and the types cannot yet be linked.
63 static bool ResolveTypes(const Type
*DestTy
, const Type
*SrcTy
,
64 SymbolTable
*DestST
, const std::string
&Name
) {
65 if (DestTy
== SrcTy
) return false; // If already equal, noop
67 // Does the type already exist in the module?
68 if (DestTy
&& !isa
<OpaqueType
>(DestTy
)) { // Yup, the type already exists...
69 if (const OpaqueType
*OT
= dyn_cast
<OpaqueType
>(SrcTy
)) {
70 const_cast<OpaqueType
*>(OT
)->refineAbstractTypeTo(DestTy
);
72 return true; // Cannot link types... neither is opaque and not-equal
74 } else { // Type not in dest module. Add it now.
75 if (DestTy
) // Type _is_ in module, just opaque...
76 const_cast<OpaqueType
*>(cast
<OpaqueType
>(DestTy
))
77 ->refineAbstractTypeTo(SrcTy
);
78 else if (!Name
.empty())
79 DestST
->insert(Name
, const_cast<Type
*>(SrcTy
));
84 static const FunctionType
*getFT(const PATypeHolder
&TH
) {
85 return cast
<FunctionType
>(TH
.get());
87 static const StructType
*getST(const PATypeHolder
&TH
) {
88 return cast
<StructType
>(TH
.get());
91 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
92 // recurses down into derived types, merging the used types if the parent types
94 static bool RecursiveResolveTypesI(const PATypeHolder
&DestTy
,
95 const PATypeHolder
&SrcTy
,
96 SymbolTable
*DestST
, const std::string
&Name
,
97 std::vector
<std::pair
<PATypeHolder
, PATypeHolder
> > &Pointers
) {
98 const Type
*SrcTyT
= SrcTy
.get();
99 const Type
*DestTyT
= DestTy
.get();
100 if (DestTyT
== SrcTyT
) return false; // If already equal, noop
102 // If we found our opaque type, resolve it now!
103 if (isa
<OpaqueType
>(DestTyT
) || isa
<OpaqueType
>(SrcTyT
))
104 return ResolveTypes(DestTyT
, SrcTyT
, DestST
, Name
);
106 // Two types cannot be resolved together if they are of different primitive
107 // type. For example, we cannot resolve an int to a float.
108 if (DestTyT
->getTypeID() != SrcTyT
->getTypeID()) return true;
110 // Otherwise, resolve the used type used by this derived type...
111 switch (DestTyT
->getTypeID()) {
112 case Type::FunctionTyID
: {
113 if (cast
<FunctionType
>(DestTyT
)->isVarArg() !=
114 cast
<FunctionType
>(SrcTyT
)->isVarArg() ||
115 cast
<FunctionType
>(DestTyT
)->getNumContainedTypes() !=
116 cast
<FunctionType
>(SrcTyT
)->getNumContainedTypes())
118 for (unsigned i
= 0, e
= getFT(DestTy
)->getNumContainedTypes(); i
!= e
; ++i
)
119 if (RecursiveResolveTypesI(getFT(DestTy
)->getContainedType(i
),
120 getFT(SrcTy
)->getContainedType(i
), DestST
, "",
125 case Type::StructTyID
: {
126 if (getST(DestTy
)->getNumContainedTypes() !=
127 getST(SrcTy
)->getNumContainedTypes()) return 1;
128 for (unsigned i
= 0, e
= getST(DestTy
)->getNumContainedTypes(); i
!= e
; ++i
)
129 if (RecursiveResolveTypesI(getST(DestTy
)->getContainedType(i
),
130 getST(SrcTy
)->getContainedType(i
), DestST
, "",
135 case Type::ArrayTyID
: {
136 const ArrayType
*DAT
= cast
<ArrayType
>(DestTy
.get());
137 const ArrayType
*SAT
= cast
<ArrayType
>(SrcTy
.get());
138 if (DAT
->getNumElements() != SAT
->getNumElements()) return true;
139 return RecursiveResolveTypesI(DAT
->getElementType(), SAT
->getElementType(),
140 DestST
, "", Pointers
);
142 case Type::PointerTyID
: {
143 // If this is a pointer type, check to see if we have already seen it. If
144 // so, we are in a recursive branch. Cut off the search now. We cannot use
145 // an associative container for this search, because the type pointers (keys
146 // in the container) change whenever types get resolved...
147 for (unsigned i
= 0, e
= Pointers
.size(); i
!= e
; ++i
)
148 if (Pointers
[i
].first
== DestTy
)
149 return Pointers
[i
].second
!= SrcTy
;
151 // Otherwise, add the current pointers to the vector to stop recursion on
153 Pointers
.push_back(std::make_pair(DestTyT
, SrcTyT
));
155 RecursiveResolveTypesI(cast
<PointerType
>(DestTy
.get())->getElementType(),
156 cast
<PointerType
>(SrcTy
.get())->getElementType(),
157 DestST
, "", Pointers
);
161 default: assert(0 && "Unexpected type!"); return true;
165 static bool RecursiveResolveTypes(const PATypeHolder
&DestTy
,
166 const PATypeHolder
&SrcTy
,
167 SymbolTable
*DestST
, const std::string
&Name
){
168 std::vector
<std::pair
<PATypeHolder
, PATypeHolder
> > PointerTypes
;
169 return RecursiveResolveTypesI(DestTy
, SrcTy
, DestST
, Name
, PointerTypes
);
173 // LinkTypes - Go through the symbol table of the Src module and see if any
174 // types are named in the src module that are not named in the Dst module.
175 // Make sure there are no type name conflicts.
176 static bool LinkTypes(Module
*Dest
, const Module
*Src
, std::string
*Err
) {
177 SymbolTable
*DestST
= &Dest
->getSymbolTable();
178 const SymbolTable
*SrcST
= &Src
->getSymbolTable();
180 // Look for a type plane for Type's...
181 SymbolTable::type_const_iterator TI
= SrcST
->type_begin();
182 SymbolTable::type_const_iterator TE
= SrcST
->type_end();
183 if (TI
== TE
) return false; // No named types, do nothing.
185 // Some types cannot be resolved immediately because they depend on other
186 // types being resolved to each other first. This contains a list of types we
187 // are waiting to recheck.
188 std::vector
<std::string
> DelayedTypesToResolve
;
190 for ( ; TI
!= TE
; ++TI
) {
191 const std::string
&Name
= TI
->first
;
192 const Type
*RHS
= TI
->second
;
194 // Check to see if this type name is already in the dest module...
195 Type
*Entry
= DestST
->lookupType(Name
);
197 if (ResolveTypes(Entry
, RHS
, DestST
, Name
)) {
198 // They look different, save the types 'till later to resolve.
199 DelayedTypesToResolve
.push_back(Name
);
203 // Iteratively resolve types while we can...
204 while (!DelayedTypesToResolve
.empty()) {
205 // Loop over all of the types, attempting to resolve them if possible...
206 unsigned OldSize
= DelayedTypesToResolve
.size();
208 // Try direct resolution by name...
209 for (unsigned i
= 0; i
!= DelayedTypesToResolve
.size(); ++i
) {
210 const std::string
&Name
= DelayedTypesToResolve
[i
];
211 Type
*T1
= SrcST
->lookupType(Name
);
212 Type
*T2
= DestST
->lookupType(Name
);
213 if (!ResolveTypes(T2
, T1
, DestST
, Name
)) {
214 // We are making progress!
215 DelayedTypesToResolve
.erase(DelayedTypesToResolve
.begin()+i
);
220 // Did we not eliminate any types?
221 if (DelayedTypesToResolve
.size() == OldSize
) {
222 // Attempt to resolve subelements of types. This allows us to merge these
223 // two types: { int* } and { opaque* }
224 for (unsigned i
= 0, e
= DelayedTypesToResolve
.size(); i
!= e
; ++i
) {
225 const std::string
&Name
= DelayedTypesToResolve
[i
];
226 PATypeHolder
T1(SrcST
->lookupType(Name
));
227 PATypeHolder
T2(DestST
->lookupType(Name
));
229 if (!RecursiveResolveTypes(T2
, T1
, DestST
, Name
)) {
230 // We are making progress!
231 DelayedTypesToResolve
.erase(DelayedTypesToResolve
.begin()+i
);
233 // Go back to the main loop, perhaps we can resolve directly by name
239 // If we STILL cannot resolve the types, then there is something wrong.
240 if (DelayedTypesToResolve
.size() == OldSize
) {
241 // Remove the symbol name from the destination.
242 DelayedTypesToResolve
.pop_back();
251 static void PrintMap(const std::map
<const Value
*, Value
*> &M
) {
252 for (std::map
<const Value
*, Value
*>::const_iterator I
= M
.begin(), E
=M
.end();
254 std::cerr
<< " Fr: " << (void*)I
->first
<< " ";
256 std::cerr
<< " To: " << (void*)I
->second
<< " ";
263 // RemapOperand - Use ValueMap to convert references from one module to another.
264 // This is somewhat sophisticated in that it can automatically handle constant
265 // references correctly as well...
266 static Value
*RemapOperand(const Value
*In
,
267 std::map
<const Value
*, Value
*> &ValueMap
) {
268 std::map
<const Value
*,Value
*>::const_iterator I
= ValueMap
.find(In
);
269 if (I
!= ValueMap
.end()) return I
->second
;
271 // Check to see if it's a constant that we are interesting in transforming.
272 if (const Constant
*CPV
= dyn_cast
<Constant
>(In
)) {
273 if ((!isa
<DerivedType
>(CPV
->getType()) && !isa
<ConstantExpr
>(CPV
)) ||
274 isa
<ConstantAggregateZero
>(CPV
))
275 return const_cast<Constant
*>(CPV
); // Simple constants stay identical.
277 Constant
*Result
= 0;
279 if (const ConstantArray
*CPA
= dyn_cast
<ConstantArray
>(CPV
)) {
280 std::vector
<Constant
*> Operands(CPA
->getNumOperands());
281 for (unsigned i
= 0, e
= CPA
->getNumOperands(); i
!= e
; ++i
)
282 Operands
[i
] =cast
<Constant
>(RemapOperand(CPA
->getOperand(i
), ValueMap
));
283 Result
= ConstantArray::get(cast
<ArrayType
>(CPA
->getType()), Operands
);
284 } else if (const ConstantStruct
*CPS
= dyn_cast
<ConstantStruct
>(CPV
)) {
285 std::vector
<Constant
*> Operands(CPS
->getNumOperands());
286 for (unsigned i
= 0, e
= CPS
->getNumOperands(); i
!= e
; ++i
)
287 Operands
[i
] =cast
<Constant
>(RemapOperand(CPS
->getOperand(i
), ValueMap
));
288 Result
= ConstantStruct::get(cast
<StructType
>(CPS
->getType()), Operands
);
289 } else if (isa
<ConstantPointerNull
>(CPV
) || isa
<UndefValue
>(CPV
)) {
290 Result
= const_cast<Constant
*>(CPV
);
291 } else if (isa
<GlobalValue
>(CPV
)) {
292 Result
= cast
<Constant
>(RemapOperand(CPV
, ValueMap
));
293 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CPV
)) {
294 if (CE
->getOpcode() == Instruction::GetElementPtr
) {
295 Value
*Ptr
= RemapOperand(CE
->getOperand(0), ValueMap
);
296 std::vector
<Constant
*> Indices
;
297 Indices
.reserve(CE
->getNumOperands()-1);
298 for (unsigned i
= 1, e
= CE
->getNumOperands(); i
!= e
; ++i
)
299 Indices
.push_back(cast
<Constant
>(RemapOperand(CE
->getOperand(i
),
302 Result
= ConstantExpr::getGetElementPtr(cast
<Constant
>(Ptr
), Indices
);
303 } else if (CE
->getNumOperands() == 1) {
305 assert(CE
->getOpcode() == Instruction::Cast
);
306 Value
*V
= RemapOperand(CE
->getOperand(0), ValueMap
);
307 Result
= ConstantExpr::getCast(cast
<Constant
>(V
), CE
->getType());
308 } else if (CE
->getNumOperands() == 3) {
309 // Select instruction
310 assert(CE
->getOpcode() == Instruction::Select
);
311 Value
*V1
= RemapOperand(CE
->getOperand(0), ValueMap
);
312 Value
*V2
= RemapOperand(CE
->getOperand(1), ValueMap
);
313 Value
*V3
= RemapOperand(CE
->getOperand(2), ValueMap
);
314 Result
= ConstantExpr::getSelect(cast
<Constant
>(V1
), cast
<Constant
>(V2
),
316 } else if (CE
->getNumOperands() == 2) {
317 // Binary operator...
318 Value
*V1
= RemapOperand(CE
->getOperand(0), ValueMap
);
319 Value
*V2
= RemapOperand(CE
->getOperand(1), ValueMap
);
321 Result
= ConstantExpr::get(CE
->getOpcode(), cast
<Constant
>(V1
),
324 assert(0 && "Unknown constant expr type!");
328 assert(0 && "Unknown type of derived type constant value!");
331 // Cache the mapping in our local map structure...
332 ValueMap
.insert(std::make_pair(In
, Result
));
336 std::cerr
<< "LinkModules ValueMap: \n";
339 std::cerr
<< "Couldn't remap value: " << (void*)In
<< " " << *In
<< "\n";
340 assert(0 && "Couldn't remap value!");
344 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
345 /// in the symbol table. This is good for all clients except for us. Go
346 /// through the trouble to force this back.
347 static void ForceRenaming(GlobalValue
*GV
, const std::string
&Name
) {
348 assert(GV
->getName() != Name
&& "Can't force rename to self");
349 SymbolTable
&ST
= GV
->getParent()->getSymbolTable();
351 // If there is a conflict, rename the conflict.
352 Value
*ConflictVal
= ST
.lookup(GV
->getType(), Name
);
353 assert(ConflictVal
&&"Why do we have to force rename if there is no conflic?");
354 GlobalValue
*ConflictGV
= cast
<GlobalValue
>(ConflictVal
);
355 assert(ConflictGV
->hasInternalLinkage() &&
356 "Not conflicting with a static global, should link instead!");
358 ConflictGV
->setName(""); // Eliminate the conflict
359 GV
->setName(Name
); // Force the name back
360 ConflictGV
->setName(Name
); // This will cause ConflictGV to get renamed
361 assert(GV
->getName() == Name
&& ConflictGV
->getName() != Name
&&
362 "ForceRenaming didn't work");
365 /// GetLinkageResult - This analyzes the two global values and determines what
366 /// the result will look like in the destination module. In particular, it
367 /// computes the resultant linkage type, computes whether the global in the
368 /// source should be copied over to the destination (replacing the existing
369 /// one), and computes whether this linkage is an error or not.
370 static bool GetLinkageResult(GlobalValue
*Dest
, GlobalValue
*Src
,
371 GlobalValue::LinkageTypes
<
, bool &LinkFromSrc
,
373 assert((!Dest
|| !Src
->hasInternalLinkage()) &&
374 "If Src has internal linkage, Dest shouldn't be set!");
376 // Linking something to nothing.
378 LT
= Src
->getLinkage();
379 } else if (Src
->isExternal()) {
380 // If Src is external or if both Src & Drc are external.. Just link the
381 // external globals, we aren't adding anything.
383 LT
= Dest
->getLinkage();
384 } else if (Dest
->isExternal()) {
385 // If Dest is external but Src is not:
387 LT
= Src
->getLinkage();
388 } else if (Src
->hasAppendingLinkage() || Dest
->hasAppendingLinkage()) {
389 if (Src
->getLinkage() != Dest
->getLinkage())
390 return Error(Err
, "Linking globals named '" + Src
->getName() +
391 "': can only link appending global with another appending global!");
392 LinkFromSrc
= true; // Special cased.
393 LT
= Src
->getLinkage();
394 } else if (Src
->hasWeakLinkage() || Src
->hasLinkOnceLinkage()) {
395 // At this point we know that Dest has LinkOnce, External or Weak linkage.
396 if (Dest
->hasLinkOnceLinkage() && Src
->hasWeakLinkage()) {
398 LT
= Src
->getLinkage();
401 LT
= Dest
->getLinkage();
403 } else if (Dest
->hasWeakLinkage() || Dest
->hasLinkOnceLinkage()) {
404 // At this point we know that Src has External linkage.
406 LT
= GlobalValue::ExternalLinkage
;
408 assert(Dest
->hasExternalLinkage() && Src
->hasExternalLinkage() &&
409 "Unexpected linkage type!");
410 return Error(Err
, "Linking globals named '" + Src
->getName() +
411 "': symbol multiply defined!");
416 // LinkGlobals - Loop through the global variables in the src module and merge
417 // them into the dest module.
418 static bool LinkGlobals(Module
*Dest
, Module
*Src
,
419 std::map
<const Value
*, Value
*> &ValueMap
,
420 std::multimap
<std::string
, GlobalVariable
*> &AppendingVars
,
421 std::map
<std::string
, GlobalValue
*> &GlobalsByName
,
423 // We will need a module level symbol table if the src module has a module
424 // level symbol table...
425 SymbolTable
*ST
= (SymbolTable
*)&Dest
->getSymbolTable();
427 // Loop over all of the globals in the src module, mapping them over as we go
428 for (Module::global_iterator I
= Src
->global_begin(), E
= Src
->global_end(); I
!= E
; ++I
) {
429 GlobalVariable
*SGV
= I
;
430 GlobalVariable
*DGV
= 0;
431 // Check to see if may have to link the global.
432 if (SGV
->hasName() && !SGV
->hasInternalLinkage())
433 if (!(DGV
= Dest
->getGlobalVariable(SGV
->getName(),
434 SGV
->getType()->getElementType()))) {
435 std::map
<std::string
, GlobalValue
*>::iterator EGV
=
436 GlobalsByName
.find(SGV
->getName());
437 if (EGV
!= GlobalsByName
.end())
438 DGV
= dyn_cast
<GlobalVariable
>(EGV
->second
);
440 // If types don't agree due to opaque types, try to resolve them.
441 RecursiveResolveTypes(SGV
->getType(), DGV
->getType(),ST
, "");
444 if (DGV
&& DGV
->hasInternalLinkage())
447 assert(SGV
->hasInitializer() || SGV
->hasExternalLinkage() &&
448 "Global must either be external or have an initializer!");
450 GlobalValue::LinkageTypes NewLinkage
;
452 if (GetLinkageResult(DGV
, SGV
, NewLinkage
, LinkFromSrc
, Err
))
456 // No linking to be performed, simply create an identical version of the
457 // symbol over in the dest module... the initializer will be filled in
458 // later by LinkGlobalInits...
459 GlobalVariable
*NewDGV
=
460 new GlobalVariable(SGV
->getType()->getElementType(),
461 SGV
->isConstant(), SGV
->getLinkage(), /*init*/0,
462 SGV
->getName(), Dest
);
464 // If the LLVM runtime renamed the global, but it is an externally visible
465 // symbol, DGV must be an existing global with internal linkage. Rename
467 if (NewDGV
->getName() != SGV
->getName() && !NewDGV
->hasInternalLinkage())
468 ForceRenaming(NewDGV
, SGV
->getName());
470 // Make sure to remember this mapping...
471 ValueMap
.insert(std::make_pair(SGV
, NewDGV
));
472 if (SGV
->hasAppendingLinkage())
473 // Keep track that this is an appending variable...
474 AppendingVars
.insert(std::make_pair(SGV
->getName(), NewDGV
));
475 } else if (DGV
->hasAppendingLinkage()) {
476 // No linking is performed yet. Just insert a new copy of the global, and
477 // keep track of the fact that it is an appending variable in the
478 // AppendingVars map. The name is cleared out so that no linkage is
480 GlobalVariable
*NewDGV
=
481 new GlobalVariable(SGV
->getType()->getElementType(),
482 SGV
->isConstant(), SGV
->getLinkage(), /*init*/0,
485 // Make sure to remember this mapping...
486 ValueMap
.insert(std::make_pair(SGV
, NewDGV
));
488 // Keep track that this is an appending variable...
489 AppendingVars
.insert(std::make_pair(SGV
->getName(), NewDGV
));
491 // Otherwise, perform the mapping as instructed by GetLinkageResult. If
492 // the types don't match, and if we are to link from the source, nuke DGV
493 // and create a new one of the appropriate type.
494 if (SGV
->getType() != DGV
->getType() && LinkFromSrc
) {
495 GlobalVariable
*NewDGV
=
496 new GlobalVariable(SGV
->getType()->getElementType(),
497 DGV
->isConstant(), DGV
->getLinkage());
498 Dest
->getGlobalList().insert(DGV
, NewDGV
);
499 DGV
->replaceAllUsesWith(ConstantExpr::getCast(NewDGV
, DGV
->getType()));
500 DGV
->eraseFromParent();
501 NewDGV
->setName(SGV
->getName());
505 DGV
->setLinkage(NewLinkage
);
508 // Inherit const as appropriate
509 DGV
->setConstant(SGV
->isConstant());
510 DGV
->setInitializer(0);
512 if (SGV
->isConstant() && !DGV
->isConstant()) {
513 if (DGV
->isExternal())
514 DGV
->setConstant(true);
516 SGV
->setLinkage(GlobalValue::ExternalLinkage
);
517 SGV
->setInitializer(0);
520 ValueMap
.insert(std::make_pair(SGV
,
521 ConstantExpr::getCast(DGV
,
529 // LinkGlobalInits - Update the initializers in the Dest module now that all
530 // globals that may be referenced are in Dest.
531 static bool LinkGlobalInits(Module
*Dest
, const Module
*Src
,
532 std::map
<const Value
*, Value
*> &ValueMap
,
535 // Loop over all of the globals in the src module, mapping them over as we go
536 for (Module::const_global_iterator I
= Src
->global_begin(), E
= Src
->global_end(); I
!= E
; ++I
){
537 const GlobalVariable
*SGV
= I
;
539 if (SGV
->hasInitializer()) { // Only process initialized GV's
540 // Figure out what the initializer looks like in the dest module...
542 cast
<Constant
>(RemapOperand(SGV
->getInitializer(), ValueMap
));
544 GlobalVariable
*DGV
= cast
<GlobalVariable
>(ValueMap
[SGV
]);
545 if (DGV
->hasInitializer()) {
546 if (SGV
->hasExternalLinkage()) {
547 if (DGV
->getInitializer() != SInit
)
548 return Error(Err
, "Global Variable Collision on '" +
549 ToStr(SGV
->getType(), Src
) +"':%"+SGV
->getName()+
550 " - Global variables have different initializers");
551 } else if (DGV
->hasLinkOnceLinkage() || DGV
->hasWeakLinkage()) {
552 // Nothing is required, mapped values will take the new global
554 } else if (SGV
->hasLinkOnceLinkage() || SGV
->hasWeakLinkage()) {
555 // Nothing is required, mapped values will take the new global
557 } else if (DGV
->hasAppendingLinkage()) {
558 assert(0 && "Appending linkage unimplemented!");
560 assert(0 && "Unknown linkage!");
563 // Copy the initializer over now...
564 DGV
->setInitializer(SInit
);
571 // LinkFunctionProtos - Link the functions together between the two modules,
572 // without doing function bodies... this just adds external function prototypes
573 // to the Dest function...
575 static bool LinkFunctionProtos(Module
*Dest
, const Module
*Src
,
576 std::map
<const Value
*, Value
*> &ValueMap
,
577 std::map
<std::string
, GlobalValue
*> &GlobalsByName
,
579 SymbolTable
*ST
= (SymbolTable
*)&Dest
->getSymbolTable();
581 // Loop over all of the functions in the src module, mapping them over as we
583 for (Module::const_iterator I
= Src
->begin(), E
= Src
->end(); I
!= E
; ++I
) {
584 const Function
*SF
= I
; // SrcFunction
586 if (SF
->hasName() && !SF
->hasInternalLinkage()) {
587 // Check to see if may have to link the function.
588 if (!(DF
= Dest
->getFunction(SF
->getName(), SF
->getFunctionType()))) {
589 std::map
<std::string
, GlobalValue
*>::iterator EF
=
590 GlobalsByName
.find(SF
->getName());
591 if (EF
!= GlobalsByName
.end())
592 DF
= dyn_cast
<Function
>(EF
->second
);
593 if (DF
&& RecursiveResolveTypes(SF
->getType(), DF
->getType(), ST
, ""))
594 DF
= 0; // FIXME: gross.
598 if (!DF
|| SF
->hasInternalLinkage() || DF
->hasInternalLinkage()) {
599 // Function does not already exist, simply insert an function signature
600 // identical to SF into the dest module...
601 Function
*NewDF
= new Function(SF
->getFunctionType(), SF
->getLinkage(),
602 SF
->getName(), Dest
);
603 NewDF
->setCallingConv(SF
->getCallingConv());
605 // If the LLVM runtime renamed the function, but it is an externally
606 // visible symbol, DF must be an existing function with internal linkage.
608 if (NewDF
->getName() != SF
->getName() && !NewDF
->hasInternalLinkage())
609 ForceRenaming(NewDF
, SF
->getName());
611 // ... and remember this mapping...
612 ValueMap
.insert(std::make_pair(SF
, NewDF
));
613 } else if (SF
->isExternal()) {
614 // If SF is external or if both SF & DF are external.. Just link the
615 // external functions, we aren't adding anything.
616 ValueMap
.insert(std::make_pair(SF
, DF
));
617 } else if (DF
->isExternal()) { // If DF is external but SF is not...
618 // Link the external functions, update linkage qualifiers
619 ValueMap
.insert(std::make_pair(SF
, DF
));
620 DF
->setLinkage(SF
->getLinkage());
622 } else if (SF
->hasWeakLinkage() || SF
->hasLinkOnceLinkage()) {
623 // At this point we know that DF has LinkOnce, Weak, or External linkage.
624 ValueMap
.insert(std::make_pair(SF
, DF
));
626 // Linkonce+Weak = Weak
627 if (DF
->hasLinkOnceLinkage() && SF
->hasWeakLinkage())
628 DF
->setLinkage(SF
->getLinkage());
630 } else if (DF
->hasWeakLinkage() || DF
->hasLinkOnceLinkage()) {
631 // At this point we know that SF has LinkOnce or External linkage.
632 ValueMap
.insert(std::make_pair(SF
, DF
));
633 if (!SF
->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
634 DF
->setLinkage(SF
->getLinkage());
636 } else if (SF
->getLinkage() != DF
->getLinkage()) {
637 return Error(Err
, "Functions named '" + SF
->getName() +
638 "' have different linkage specifiers!");
639 } else if (SF
->hasExternalLinkage()) {
640 // The function is defined in both modules!!
641 return Error(Err
, "Function '" +
642 ToStr(SF
->getFunctionType(), Src
) + "':\"" +
643 SF
->getName() + "\" - Function is already defined!");
645 assert(0 && "Unknown linkage configuration found!");
651 // LinkFunctionBody - Copy the source function over into the dest function and
652 // fix up references to values. At this point we know that Dest is an external
653 // function, and that Src is not.
654 static bool LinkFunctionBody(Function
*Dest
, Function
*Src
,
655 std::map
<const Value
*, Value
*> &GlobalMap
,
657 assert(Src
&& Dest
&& Dest
->isExternal() && !Src
->isExternal());
659 // Go through and convert function arguments over, remembering the mapping.
660 Function::arg_iterator DI
= Dest
->arg_begin();
661 for (Function::arg_iterator I
= Src
->arg_begin(), E
= Src
->arg_end();
663 DI
->setName(I
->getName()); // Copy the name information over...
665 // Add a mapping to our local map
666 GlobalMap
.insert(std::make_pair(I
, DI
));
669 // Splice the body of the source function into the dest function.
670 Dest
->getBasicBlockList().splice(Dest
->end(), Src
->getBasicBlockList());
672 // At this point, all of the instructions and values of the function are now
673 // copied over. The only problem is that they are still referencing values in
674 // the Source function as operands. Loop through all of the operands of the
675 // functions and patch them up to point to the local versions...
677 for (Function::iterator BB
= Dest
->begin(), BE
= Dest
->end(); BB
!= BE
; ++BB
)
678 for (BasicBlock::iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
; ++I
)
679 for (Instruction::op_iterator OI
= I
->op_begin(), OE
= I
->op_end();
681 if (!isa
<Instruction
>(*OI
) && !isa
<BasicBlock
>(*OI
))
682 *OI
= RemapOperand(*OI
, GlobalMap
);
684 // There is no need to map the arguments anymore.
685 for (Function::arg_iterator I
= Src
->arg_begin(), E
= Src
->arg_end(); I
!= E
; ++I
)
692 // LinkFunctionBodies - Link in the function bodies that are defined in the
693 // source module into the DestModule. This consists basically of copying the
694 // function over and fixing up references to values.
695 static bool LinkFunctionBodies(Module
*Dest
, Module
*Src
,
696 std::map
<const Value
*, Value
*> &ValueMap
,
699 // Loop over all of the functions in the src module, mapping them over as we
701 for (Module::iterator SF
= Src
->begin(), E
= Src
->end(); SF
!= E
; ++SF
) {
702 if (!SF
->isExternal()) { // No body if function is external
703 Function
*DF
= cast
<Function
>(ValueMap
[SF
]); // Destination function
705 // DF not external SF external?
706 if (DF
->isExternal()) {
707 // Only provide the function body if there isn't one already.
708 if (LinkFunctionBody(DF
, SF
, ValueMap
, Err
))
716 // LinkAppendingVars - If there were any appending global variables, link them
717 // together now. Return true on error.
718 static bool LinkAppendingVars(Module
*M
,
719 std::multimap
<std::string
, GlobalVariable
*> &AppendingVars
,
720 std::string
*ErrorMsg
) {
721 if (AppendingVars
.empty()) return false; // Nothing to do.
723 // Loop over the multimap of appending vars, processing any variables with the
724 // same name, forming a new appending global variable with both of the
725 // initializers merged together, then rewrite references to the old variables
727 std::vector
<Constant
*> Inits
;
728 while (AppendingVars
.size() > 1) {
729 // Get the first two elements in the map...
730 std::multimap
<std::string
,
731 GlobalVariable
*>::iterator Second
= AppendingVars
.begin(), First
=Second
++;
733 // If the first two elements are for different names, there is no pair...
734 // Otherwise there is a pair, so link them together...
735 if (First
->first
== Second
->first
) {
736 GlobalVariable
*G1
= First
->second
, *G2
= Second
->second
;
737 const ArrayType
*T1
= cast
<ArrayType
>(G1
->getType()->getElementType());
738 const ArrayType
*T2
= cast
<ArrayType
>(G2
->getType()->getElementType());
740 // Check to see that they two arrays agree on type...
741 if (T1
->getElementType() != T2
->getElementType())
742 return Error(ErrorMsg
,
743 "Appending variables with different element types need to be linked!");
744 if (G1
->isConstant() != G2
->isConstant())
745 return Error(ErrorMsg
,
746 "Appending variables linked with different const'ness!");
748 unsigned NewSize
= T1
->getNumElements() + T2
->getNumElements();
749 ArrayType
*NewType
= ArrayType::get(T1
->getElementType(), NewSize
);
751 // Create the new global variable...
753 new GlobalVariable(NewType
, G1
->isConstant(), G1
->getLinkage(),
754 /*init*/0, First
->first
, M
);
756 // Merge the initializer...
757 Inits
.reserve(NewSize
);
758 if (ConstantArray
*I
= dyn_cast
<ConstantArray
>(G1
->getInitializer())) {
759 for (unsigned i
= 0, e
= T1
->getNumElements(); i
!= e
; ++i
)
760 Inits
.push_back(I
->getOperand(i
));
762 assert(isa
<ConstantAggregateZero
>(G1
->getInitializer()));
763 Constant
*CV
= Constant::getNullValue(T1
->getElementType());
764 for (unsigned i
= 0, e
= T1
->getNumElements(); i
!= e
; ++i
)
767 if (ConstantArray
*I
= dyn_cast
<ConstantArray
>(G2
->getInitializer())) {
768 for (unsigned i
= 0, e
= T2
->getNumElements(); i
!= e
; ++i
)
769 Inits
.push_back(I
->getOperand(i
));
771 assert(isa
<ConstantAggregateZero
>(G2
->getInitializer()));
772 Constant
*CV
= Constant::getNullValue(T2
->getElementType());
773 for (unsigned i
= 0, e
= T2
->getNumElements(); i
!= e
; ++i
)
776 NG
->setInitializer(ConstantArray::get(NewType
, Inits
));
779 // Replace any uses of the two global variables with uses of the new
782 // FIXME: This should rewrite simple/straight-forward uses such as
783 // getelementptr instructions to not use the Cast!
784 G1
->replaceAllUsesWith(ConstantExpr::getCast(NG
, G1
->getType()));
785 G2
->replaceAllUsesWith(ConstantExpr::getCast(NG
, G2
->getType()));
787 // Remove the two globals from the module now...
788 M
->getGlobalList().erase(G1
);
789 M
->getGlobalList().erase(G2
);
791 // Put the new global into the AppendingVars map so that we can handle
792 // linking of more than two vars...
795 AppendingVars
.erase(First
);
802 // LinkModules - This function links two modules together, with the resulting
803 // left module modified to be the composite of the two input modules. If an
804 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
805 // the problem. Upon failure, the Dest module could be in a modified state, and
806 // shouldn't be relied on to be consistent.
808 Linker::LinkModules(Module
*Dest
, Module
*Src
, std::string
*ErrorMsg
) {
809 assert(Dest
!= 0 && "Invalid Destination module");
810 assert(Src
!= 0 && "Invalid Source Module");
812 if (Dest
->getEndianness() == Module::AnyEndianness
)
813 Dest
->setEndianness(Src
->getEndianness());
814 if (Dest
->getPointerSize() == Module::AnyPointerSize
)
815 Dest
->setPointerSize(Src
->getPointerSize());
816 if (Dest
->getTargetTriple().empty())
817 Dest
->setTargetTriple(Src
->getTargetTriple());
819 if (Src
->getEndianness() != Module::AnyEndianness
&&
820 Dest
->getEndianness() != Src
->getEndianness())
821 std::cerr
<< "WARNING: Linking two modules of different endianness!\n";
822 if (Src
->getPointerSize() != Module::AnyPointerSize
&&
823 Dest
->getPointerSize() != Src
->getPointerSize())
824 std::cerr
<< "WARNING: Linking two modules of different pointer size!\n";
825 if (!Src
->getTargetTriple().empty() &&
826 Dest
->getTargetTriple() != Src
->getTargetTriple())
827 std::cerr
<< "WARNING: Linking two modules of different target triples!\n";
829 // Update the destination module's dependent libraries list with the libraries
830 // from the source module. There's no opportunity for duplicates here as the
831 // Module ensures that duplicate insertions are discarded.
832 Module::lib_iterator SI
= Src
->lib_begin();
833 Module::lib_iterator SE
= Src
->lib_end();
835 Dest
->addLibrary(*SI
);
839 // LinkTypes - Go through the symbol table of the Src module and see if any
840 // types are named in the src module that are not named in the Dst module.
841 // Make sure there are no type name conflicts.
842 if (LinkTypes(Dest
, Src
, ErrorMsg
)) return true;
844 // ValueMap - Mapping of values from what they used to be in Src, to what they
846 std::map
<const Value
*, Value
*> ValueMap
;
848 // AppendingVars - Keep track of global variables in the destination module
849 // with appending linkage. After the module is linked together, they are
850 // appended and the module is rewritten.
851 std::multimap
<std::string
, GlobalVariable
*> AppendingVars
;
853 // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
854 // linking by separating globals by type. Until PR411 is fixed, we replicate
855 // it's functionality here.
856 std::map
<std::string
, GlobalValue
*> GlobalsByName
;
858 for (Module::global_iterator I
= Dest
->global_begin(), E
= Dest
->global_end(); I
!= E
; ++I
) {
859 // Add all of the appending globals already in the Dest module to
861 if (I
->hasAppendingLinkage())
862 AppendingVars
.insert(std::make_pair(I
->getName(), I
));
864 // Keep track of all globals by name.
865 if (!I
->hasInternalLinkage() && I
->hasName())
866 GlobalsByName
[I
->getName()] = I
;
869 // Keep track of all globals by name.
870 for (Module::iterator I
= Dest
->begin(), E
= Dest
->end(); I
!= E
; ++I
)
871 if (!I
->hasInternalLinkage() && I
->hasName())
872 GlobalsByName
[I
->getName()] = I
;
874 // Insert all of the globals in src into the Dest module... without linking
875 // initializers (which could refer to functions not yet mapped over).
876 if (LinkGlobals(Dest
, Src
, ValueMap
, AppendingVars
, GlobalsByName
, ErrorMsg
))
879 // Link the functions together between the two modules, without doing function
880 // bodies... this just adds external function prototypes to the Dest
881 // function... We do this so that when we begin processing function bodies,
882 // all of the global values that may be referenced are available in our
884 if (LinkFunctionProtos(Dest
, Src
, ValueMap
, GlobalsByName
, ErrorMsg
))
887 // Update the initializers in the Dest module now that all globals that may
888 // be referenced are in Dest.
889 if (LinkGlobalInits(Dest
, Src
, ValueMap
, ErrorMsg
)) return true;
891 // Link in the function bodies that are defined in the source module into the
892 // DestModule. This consists basically of copying the function over and
893 // fixing up references to values.
894 if (LinkFunctionBodies(Dest
, Src
, ValueMap
, ErrorMsg
)) return true;
896 // If there were any appending global variables, link them together now.
897 if (LinkAppendingVars(Dest
, AppendingVars
, ErrorMsg
)) return true;
899 // If the source library's module id is in the dependent library list of the
900 // destination library, remove it since that module is now linked in.
902 modId
.setFile(Src
->getModuleIdentifier());
903 if (!modId
.isEmpty())
904 Dest
->removeLibrary(modId
.getBasename());