1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Instructions.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/ValueSymbolTable.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/Transforms/Utils/ValueMapper.h"
34 // Error - Simple wrapper function to conditionally assign to E and return true.
35 // This just makes error return conditions a little bit simpler...
36 static inline bool Error(std::string *E, const Twine &Message) {
37 if (E) *E = Message.str();
41 // Function: ResolveTypes()
44 // Attempt to link the two specified types together.
47 // DestTy - The type to which we wish to resolve.
48 // SrcTy - The original type which we want to resolve.
51 // DestST - The symbol table in which the new type should be placed.
54 // true - There is an error and the types cannot yet be linked.
57 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
58 if (DestTy == SrcTy) return false; // If already equal, noop
59 assert(DestTy && SrcTy && "Can't handle null types");
61 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
62 // Type _is_ in module, just opaque...
63 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
64 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
65 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
67 return true; // Cannot link types... not-equal and neither is opaque.
72 /// LinkerTypeMap - This implements a map of types that is stable
73 /// even if types are resolved/refined to other types. This is not a general
74 /// purpose map, it is specific to the linker's use.
76 class LinkerTypeMap : public AbstractTypeUser {
77 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
80 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
81 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
85 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
86 E = TheMap.end(); I != E; ++I)
87 I->first->removeAbstractTypeUser(this);
90 /// lookup - Return the value for the specified type or null if it doesn't
92 const Type *lookup(const Type *Ty) const {
93 TheMapTy::const_iterator I = TheMap.find(Ty);
94 if (I != TheMap.end()) return I->second;
98 /// insert - This returns true if the pointer was new to the set, false if it
99 /// was already in the set.
100 bool insert(const Type *Src, const Type *Dst) {
101 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
102 return false; // Already in map.
103 if (Src->isAbstract())
104 Src->addAbstractTypeUser(this);
109 /// refineAbstractType - The callback method invoked when an abstract type is
110 /// resolved to another type. An object must override this method to update
111 /// its internal state to reference NewType instead of OldType.
113 virtual void refineAbstractType(const DerivedType *OldTy,
115 TheMapTy::iterator I = TheMap.find(OldTy);
116 const Type *DstTy = I->second;
119 if (OldTy->isAbstract())
120 OldTy->removeAbstractTypeUser(this);
122 // Don't reinsert into the map if the key is concrete now.
123 if (NewTy->isAbstract())
124 insert(NewTy, DstTy);
127 /// The other case which AbstractTypeUsers must be aware of is when a type
128 /// makes the transition from being abstract (where it has clients on it's
129 /// AbstractTypeUsers list) to concrete (where it does not). This method
130 /// notifies ATU's when this occurs for a type.
131 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
133 AbsTy->removeAbstractTypeUser(this);
137 virtual void dump() const {
138 dbgs() << "AbstractTypeSet!\n";
144 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
145 // recurses down into derived types, merging the used types if the parent types
147 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
148 LinkerTypeMap &Pointers) {
149 if (DstTy == SrcTy) return false; // If already equal, noop
151 // If we found our opaque type, resolve it now!
152 if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy())
153 return ResolveTypes(DstTy, SrcTy);
155 // Two types cannot be resolved together if they are of different primitive
156 // type. For example, we cannot resolve an int to a float.
157 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
159 // If neither type is abstract, then they really are just different types.
160 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
163 // Otherwise, resolve the used type used by this derived type...
164 switch (DstTy->getTypeID()) {
167 case Type::FunctionTyID: {
168 const FunctionType *DstFT = cast<FunctionType>(DstTy);
169 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
170 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
171 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
174 // Use TypeHolder's so recursive resolution won't break us.
175 PATypeHolder ST(SrcFT), DT(DstFT);
176 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
177 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
178 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
183 case Type::StructTyID: {
184 const StructType *DstST = cast<StructType>(DstTy);
185 const StructType *SrcST = cast<StructType>(SrcTy);
186 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
189 PATypeHolder ST(SrcST), DT(DstST);
190 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
191 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
192 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
197 case Type::ArrayTyID: {
198 const ArrayType *DAT = cast<ArrayType>(DstTy);
199 const ArrayType *SAT = cast<ArrayType>(SrcTy);
200 if (DAT->getNumElements() != SAT->getNumElements()) return true;
201 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
204 case Type::VectorTyID: {
205 const VectorType *DVT = cast<VectorType>(DstTy);
206 const VectorType *SVT = cast<VectorType>(SrcTy);
207 if (DVT->getNumElements() != SVT->getNumElements()) return true;
208 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
211 case Type::PointerTyID: {
212 const PointerType *DstPT = cast<PointerType>(DstTy);
213 const PointerType *SrcPT = cast<PointerType>(SrcTy);
215 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
218 // If this is a pointer type, check to see if we have already seen it. If
219 // so, we are in a recursive branch. Cut off the search now. We cannot use
220 // an associative container for this search, because the type pointers (keys
221 // in the container) change whenever types get resolved.
222 if (SrcPT->isAbstract())
223 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
224 return ExistingDestTy != DstPT;
226 if (DstPT->isAbstract())
227 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
228 return ExistingSrcTy != SrcPT;
229 // Otherwise, add the current pointers to the vector to stop recursion on
231 if (DstPT->isAbstract())
232 Pointers.insert(DstPT, SrcPT);
233 if (SrcPT->isAbstract())
234 Pointers.insert(SrcPT, DstPT);
236 return RecursiveResolveTypesI(DstPT->getElementType(),
237 SrcPT->getElementType(), Pointers);
242 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
243 LinkerTypeMap PointerTypes;
244 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
248 // LinkTypes - Go through the symbol table of the Src module and see if any
249 // types are named in the src module that are not named in the Dst module.
250 // Make sure there are no type name conflicts.
251 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
252 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
253 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
255 // Look for a type plane for Type's...
256 TypeSymbolTable::const_iterator TI = SrcST->begin();
257 TypeSymbolTable::const_iterator TE = SrcST->end();
258 if (TI == TE) return false; // No named types, do nothing.
260 // Some types cannot be resolved immediately because they depend on other
261 // types being resolved to each other first. This contains a list of types we
262 // are waiting to recheck.
263 std::vector<std::string> DelayedTypesToResolve;
265 for ( ; TI != TE; ++TI ) {
266 const std::string &Name = TI->first;
267 const Type *RHS = TI->second;
269 // Check to see if this type name is already in the dest module.
270 Type *Entry = DestST->lookup(Name);
272 // If the name is just in the source module, bring it over to the dest.
275 DestST->insert(Name, const_cast<Type*>(RHS));
276 } else if (ResolveTypes(Entry, RHS)) {
277 // They look different, save the types 'till later to resolve.
278 DelayedTypesToResolve.push_back(Name);
282 // Iteratively resolve types while we can...
283 while (!DelayedTypesToResolve.empty()) {
284 // Loop over all of the types, attempting to resolve them if possible...
285 unsigned OldSize = DelayedTypesToResolve.size();
287 // Try direct resolution by name...
288 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
289 const std::string &Name = DelayedTypesToResolve[i];
290 Type *T1 = SrcST->lookup(Name);
291 Type *T2 = DestST->lookup(Name);
292 if (!ResolveTypes(T2, T1)) {
293 // We are making progress!
294 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
299 // Did we not eliminate any types?
300 if (DelayedTypesToResolve.size() == OldSize) {
301 // Attempt to resolve subelements of types. This allows us to merge these
302 // two types: { int* } and { opaque* }
303 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
304 const std::string &Name = DelayedTypesToResolve[i];
305 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
306 // We are making progress!
307 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
309 // Go back to the main loop, perhaps we can resolve directly by name
315 // If we STILL cannot resolve the types, then there is something wrong.
316 if (DelayedTypesToResolve.size() == OldSize) {
317 // Remove the symbol name from the destination.
318 DelayedTypesToResolve.pop_back();
327 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
328 /// in the symbol table. This is good for all clients except for us. Go
329 /// through the trouble to force this back.
330 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
331 assert(GV->getName() != Name && "Can't force rename to self");
332 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
334 // If there is a conflict, rename the conflict.
335 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
336 assert(ConflictGV->hasLocalLinkage() &&
337 "Not conflicting with a static global, should link instead!");
338 GV->takeName(ConflictGV);
339 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
340 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
342 GV->setName(Name); // Force the name back
346 /// CopyGVAttributes - copy additional attributes (those not needed to construct
347 /// a GlobalValue) from the SrcGV to the DestGV.
348 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
349 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
350 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
351 DestGV->copyAttributesFrom(SrcGV);
352 DestGV->setAlignment(Alignment);
355 /// GetLinkageResult - This analyzes the two global values and determines what
356 /// the result will look like in the destination module. In particular, it
357 /// computes the resultant linkage type, computes whether the global in the
358 /// source should be copied over to the destination (replacing the existing
359 /// one), and computes whether this linkage is an error or not. It also performs
360 /// visibility checks: we cannot link together two symbols with different
362 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
363 GlobalValue::LinkageTypes <, bool &LinkFromSrc,
365 assert((!Dest || !Src->hasLocalLinkage()) &&
366 "If Src has internal linkage, Dest shouldn't be set!");
368 // Linking something to nothing.
370 LT = Src->getLinkage();
371 } else if (Src->isDeclaration()) {
372 // If Src is external or if both Src & Dest are external.. Just link the
373 // external globals, we aren't adding anything.
374 if (Src->hasDLLImportLinkage()) {
375 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
376 if (Dest->isDeclaration()) {
378 LT = Src->getLinkage();
380 } else if (Dest->hasExternalWeakLinkage()) {
381 // If the Dest is weak, use the source linkage.
383 LT = Src->getLinkage();
386 LT = Dest->getLinkage();
388 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
389 // If Dest is external but Src is not:
391 LT = Src->getLinkage();
392 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
393 if (Src->getLinkage() != Dest->getLinkage())
394 return Error(Err, "Linking globals named '" + Src->getName() +
395 "': can only link appending global with another appending global!");
396 LinkFromSrc = true; // Special cased.
397 LT = Src->getLinkage();
398 } else if (Src->isWeakForLinker()) {
399 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
401 if (Dest->hasExternalWeakLinkage() ||
402 Dest->hasAvailableExternallyLinkage() ||
403 (Dest->hasLinkOnceLinkage() &&
404 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
406 LT = Src->getLinkage();
409 LT = Dest->getLinkage();
411 } else if (Dest->isWeakForLinker()) {
412 // At this point we know that Src has External* or DLL* linkage.
413 if (Src->hasExternalWeakLinkage()) {
415 LT = Dest->getLinkage();
418 LT = GlobalValue::ExternalLinkage;
421 assert((Dest->hasExternalLinkage() ||
422 Dest->hasDLLImportLinkage() ||
423 Dest->hasDLLExportLinkage() ||
424 Dest->hasExternalWeakLinkage()) &&
425 (Src->hasExternalLinkage() ||
426 Src->hasDLLImportLinkage() ||
427 Src->hasDLLExportLinkage() ||
428 Src->hasExternalWeakLinkage()) &&
429 "Unexpected linkage type!");
430 return Error(Err, "Linking globals named '" + Src->getName() +
431 "': symbol multiply defined!");
435 if (Dest && Src->getVisibility() != Dest->getVisibility())
436 if (!Src->isDeclaration() && !Dest->isDeclaration())
437 return Error(Err, "Linking globals named '" + Src->getName() +
438 "': symbols have different visibilities!");
442 // Insert all of the named mdnoes in Src into the Dest module.
443 static void LinkNamedMDNodes(Module *Dest, Module *Src,
444 ValueToValueMapTy &ValueMap) {
445 for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
446 E = Src->named_metadata_end(); I != E; ++I) {
447 const NamedMDNode *SrcNMD = I;
448 NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName());
449 // Add Src elements into Dest node.
450 for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
451 DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i),
457 // RequiresUnique - Returns true if the global variable needs to be
458 // unique. I.e., there shouldn't be a new global variable created in the
459 // destination Module, rather the source variable's initializer needs to be
460 // identical to the destination variable's initializer.
461 static bool RequiresUnique(const GlobalVariable *SGV,
462 const GlobalVariable *DGV) {
463 const StringRef SrcSec(SGV->getSection());
464 const StringRef DstSec(DGV->getSection());
466 // The Objective-C __image_info section should be unique.
467 if (SrcSec == DstSec &&
468 (SrcSec.find("__objc_imageinfo") != StringRef::npos ||
469 SrcSec.find("__image_info") != StringRef::npos))
475 // LinkGlobals - Loop through the global variables in the src module and merge
476 // them into the dest module.
477 static bool LinkGlobals(Module *Dest, const Module *Src,
478 ValueToValueMapTy &ValueMap,
479 std::multimap<std::string, GlobalVariable *> &AppendingVars,
481 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
483 // Loop over all of the globals in the src module, mapping them over as we go
484 for (Module::const_global_iterator I = Src->global_begin(),
485 E = Src->global_end(); I != E; ++I) {
486 const GlobalVariable *SGV = I;
487 GlobalValue *DGV = 0;
489 GlobalValue *SymTabGV =
490 cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
492 // Check to see if the symbol exists in the destination module and needs to
493 // be merged instead of replaced.
495 const GlobalVariable *GV = dyn_cast<GlobalVariable>(SymTabGV);
496 if (GV && RequiresUnique(SGV, GV)) {
497 // Make sure to remember this mapping.
498 ValueMap[SGV] = SymTabGV;
503 // Check to see if we may have to link the global with a global, alias, or
505 if (SGV->hasName() && !SGV->hasLocalLinkage())
508 // If we found a global with the same name in the dest module, but it has
509 // internal linkage, we are really not doing any linkage here.
510 if (DGV && DGV->hasLocalLinkage())
513 // If types don't agree due to opaque types, try to resolve them.
514 if (DGV && DGV->getType() != SGV->getType())
515 RecursiveResolveTypes(SGV->getType(), DGV->getType());
517 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
518 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
519 "Global must either be external or have an initializer!");
521 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
522 bool LinkFromSrc = false;
523 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
527 // No linking to be performed, simply create an identical version of the
528 // symbol over in the dest module... the initializer will be filled in
529 // later by LinkGlobalInits.
530 GlobalVariable *NewDGV =
531 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
532 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
533 SGV->getName(), 0, false,
534 SGV->getType()->getAddressSpace());
535 // Propagate alignment, visibility and section info.
536 CopyGVAttributes(NewDGV, SGV);
538 // If the LLVM runtime renamed the global, but it is an externally visible
539 // symbol, DGV must be an existing global with internal linkage. Rename
541 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
542 ForceRenaming(NewDGV, SGV->getName());
544 // Make sure to remember this mapping.
545 ValueMap[SGV] = NewDGV;
547 // Keep track that this is an appending variable.
548 if (SGV->hasAppendingLinkage())
549 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
553 // If the visibilities of the symbols disagree and the destination is a
554 // prototype, take the visibility of its input.
555 if (DGV->isDeclaration())
556 DGV->setVisibility(SGV->getVisibility());
558 if (DGV->hasAppendingLinkage()) {
559 // No linking is performed yet. Just insert a new copy of the global, and
560 // keep track of the fact that it is an appending variable in the
561 // AppendingVars map. The name is cleared out so that no linkage is
563 GlobalVariable *NewDGV =
564 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
565 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
567 SGV->getType()->getAddressSpace());
569 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
570 NewDGV->setAlignment(DGV->getAlignment());
571 // Propagate alignment, section and visibility info.
572 CopyGVAttributes(NewDGV, SGV);
574 // Make sure to remember this mapping...
575 ValueMap[SGV] = NewDGV;
577 // Keep track that this is an appending variable...
578 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
583 if (isa<GlobalAlias>(DGV))
584 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
585 "': symbol multiple defined");
587 // If the types don't match, and if we are to link from the source, nuke
588 // DGV and create a new one of the appropriate type. Note that the thing
589 // we are replacing may be a function (if a prototype, weak, etc) or a
591 GlobalVariable *NewDGV =
592 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
593 SGV->isConstant(), NewLinkage, /*init*/0,
594 DGV->getName(), 0, false,
595 SGV->getType()->getAddressSpace());
597 // Propagate alignment, section, and visibility info.
598 CopyGVAttributes(NewDGV, SGV);
599 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
602 // DGV will conflict with NewDGV because they both had the same
603 // name. We must erase this now so ForceRenaming doesn't assert
604 // because DGV might not have internal linkage.
605 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
606 Var->eraseFromParent();
608 cast<Function>(DGV)->eraseFromParent();
610 // If the symbol table renamed the global, but it is an externally visible
611 // symbol, DGV must be an existing global with internal linkage. Rename.
612 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
613 ForceRenaming(NewDGV, SGV->getName());
615 // Inherit const as appropriate.
616 NewDGV->setConstant(SGV->isConstant());
618 // Make sure to remember this mapping.
619 ValueMap[SGV] = NewDGV;
623 // Not "link from source", keep the one in the DestModule and remap the
626 // Special case for const propagation.
627 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
628 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
629 DGVar->setConstant(true);
631 // SGV is global, but DGV is alias.
632 if (isa<GlobalAlias>(DGV)) {
633 // The only valid mappings are:
634 // - SGV is external declaration, which is effectively a no-op.
635 // - SGV is weak, when we just need to throw SGV out.
636 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
637 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
638 "': symbol multiple defined");
641 // Set calculated linkage
642 DGV->setLinkage(NewLinkage);
644 // Make sure to remember this mapping...
645 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
650 static GlobalValue::LinkageTypes
651 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
652 GlobalValue::LinkageTypes SL = SGV->getLinkage();
653 GlobalValue::LinkageTypes DL = DGV->getLinkage();
654 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
655 return GlobalValue::ExternalLinkage;
656 else if (SL == GlobalValue::WeakAnyLinkage ||
657 DL == GlobalValue::WeakAnyLinkage)
658 return GlobalValue::WeakAnyLinkage;
659 else if (SL == GlobalValue::WeakODRLinkage ||
660 DL == GlobalValue::WeakODRLinkage)
661 return GlobalValue::WeakODRLinkage;
662 else if (SL == GlobalValue::InternalLinkage &&
663 DL == GlobalValue::InternalLinkage)
664 return GlobalValue::InternalLinkage;
665 else if (SL == GlobalValue::LinkerPrivateLinkage &&
666 DL == GlobalValue::LinkerPrivateLinkage)
667 return GlobalValue::LinkerPrivateLinkage;
668 else if (SL == GlobalValue::LinkerPrivateWeakLinkage &&
669 DL == GlobalValue::LinkerPrivateWeakLinkage)
670 return GlobalValue::LinkerPrivateWeakLinkage;
671 else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage &&
672 DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage)
673 return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
675 assert (SL == GlobalValue::PrivateLinkage &&
676 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
677 return GlobalValue::PrivateLinkage;
681 // LinkAlias - Loop through the alias in the src module and link them into the
682 // dest module. We're assuming, that all functions/global variables were already
684 static bool LinkAlias(Module *Dest, const Module *Src,
685 ValueToValueMapTy &ValueMap,
687 // Loop over all alias in the src module
688 for (Module::const_alias_iterator I = Src->alias_begin(),
689 E = Src->alias_end(); I != E; ++I) {
690 const GlobalAlias *SGA = I;
691 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
692 GlobalAlias *NewGA = NULL;
694 // Globals were already linked, thus we can just query ValueMap for variant
695 // of SAliasee in Dest.
696 ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee);
697 assert(VMI != ValueMap.end() && "Aliasee not linked");
698 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
699 GlobalValue* DGV = NULL;
701 // Try to find something 'similar' to SGA in destination module.
702 if (!DGV && !SGA->hasLocalLinkage()) {
703 DGV = Dest->getNamedAlias(SGA->getName());
705 // If types don't agree due to opaque types, try to resolve them.
706 if (DGV && DGV->getType() != SGA->getType())
707 RecursiveResolveTypes(SGA->getType(), DGV->getType());
710 if (!DGV && !SGA->hasLocalLinkage()) {
711 DGV = Dest->getGlobalVariable(SGA->getName());
713 // If types don't agree due to opaque types, try to resolve them.
714 if (DGV && DGV->getType() != SGA->getType())
715 RecursiveResolveTypes(SGA->getType(), DGV->getType());
718 if (!DGV && !SGA->hasLocalLinkage()) {
719 DGV = Dest->getFunction(SGA->getName());
721 // If types don't agree due to opaque types, try to resolve them.
722 if (DGV && DGV->getType() != SGA->getType())
723 RecursiveResolveTypes(SGA->getType(), DGV->getType());
726 // No linking to be performed on internal stuff.
727 if (DGV && DGV->hasLocalLinkage())
730 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
731 // Types are known to be the same, check whether aliasees equal. As
732 // globals are already linked we just need query ValueMap to find the
734 if (DAliasee == DGA->getAliasedGlobal()) {
735 // This is just two copies of the same alias. Propagate linkage, if
737 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
740 // Proceed to 'common' steps
742 return Error(Err, "Alias Collision on '" + SGA->getName()+
743 "': aliases have different aliasees");
744 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
745 // The only allowed way is to link alias with external declaration or weak
747 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
748 // But only if aliasee is global too...
749 if (!isa<GlobalVariable>(DAliasee))
750 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
751 "': aliasee is not global variable");
753 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
754 SGA->getName(), DAliasee, Dest);
755 CopyGVAttributes(NewGA, SGA);
757 // Any uses of DGV need to change to NewGA, with cast, if needed.
758 if (SGA->getType() != DGVar->getType())
759 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
762 DGVar->replaceAllUsesWith(NewGA);
764 // DGVar will conflict with NewGA because they both had the same
765 // name. We must erase this now so ForceRenaming doesn't assert
766 // because DGV might not have internal linkage.
767 DGVar->eraseFromParent();
769 // Proceed to 'common' steps
771 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
772 "': symbol multiple defined");
773 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
774 // The only allowed way is to link alias with external declaration or weak
776 if (DF->isDeclaration() || DF->isWeakForLinker()) {
777 // But only if aliasee is function too...
778 if (!isa<Function>(DAliasee))
779 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
780 "': aliasee is not function");
782 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
783 SGA->getName(), DAliasee, Dest);
784 CopyGVAttributes(NewGA, SGA);
786 // Any uses of DF need to change to NewGA, with cast, if needed.
787 if (SGA->getType() != DF->getType())
788 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
791 DF->replaceAllUsesWith(NewGA);
793 // DF will conflict with NewGA because they both had the same
794 // name. We must erase this now so ForceRenaming doesn't assert
795 // because DF might not have internal linkage.
796 DF->eraseFromParent();
798 // Proceed to 'common' steps
800 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
801 "': symbol multiple defined");
803 // No linking to be performed, simply create an identical version of the
804 // alias over in the dest module...
805 Constant *Aliasee = DAliasee;
806 // Fixup aliases to bitcasts. Note that aliases to GEPs are still broken
807 // by this, but aliases to GEPs are broken to a lot of other things, so
808 // it's less important.
809 if (SGA->getType() != DAliasee->getType())
810 Aliasee = ConstantExpr::getBitCast(DAliasee, SGA->getType());
811 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
812 SGA->getName(), Aliasee, Dest);
813 CopyGVAttributes(NewGA, SGA);
815 // Proceed to 'common' steps
818 assert(NewGA && "No alias was created in destination module!");
820 // If the symbol table renamed the alias, but it is an externally visible
821 // symbol, DGA must be an global value with internal linkage. Rename it.
822 if (NewGA->getName() != SGA->getName() &&
823 !NewGA->hasLocalLinkage())
824 ForceRenaming(NewGA, SGA->getName());
826 // Remember this mapping so uses in the source module get remapped
827 // later by MapValue.
828 ValueMap[SGA] = NewGA;
835 // LinkGlobalInits - Update the initializers in the Dest module now that all
836 // globals that may be referenced are in Dest.
837 static bool LinkGlobalInits(Module *Dest, const Module *Src,
838 ValueToValueMapTy &ValueMap,
840 // Loop over all of the globals in the src module, mapping them over as we go
841 for (Module::const_global_iterator I = Src->global_begin(),
842 E = Src->global_end(); I != E; ++I) {
843 const GlobalVariable *SGV = I;
845 if (SGV->hasInitializer()) { // Only process initialized GV's
846 // Figure out what the initializer looks like in the dest module...
848 cast<Constant>(MapValue(SGV->getInitializer(), ValueMap, true));
849 // Grab destination global variable or alias.
850 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
852 // If dest is a global variable, check that initializers match.
853 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
854 if (DGVar->hasInitializer()) {
855 if (SGV->hasExternalLinkage() || RequiresUnique(SGV, DGVar)) {
856 if (DGVar->getInitializer() != SInit)
857 return Error(Err, "Global Variable Collision on '" +
859 "': global variables have different initializers");
860 } else if (DGVar->isWeakForLinker()) {
861 // Nothing is required, mapped values will take the new global
863 } else if (SGV->isWeakForLinker()) {
864 // Nothing is required, mapped values will take the new global
866 } else if (DGVar->hasAppendingLinkage()) {
867 llvm_unreachable("Appending linkage unimplemented!");
869 llvm_unreachable("Unknown linkage!");
872 // Copy the initializer over now...
873 DGVar->setInitializer(SInit);
876 // Destination is alias, the only valid situation is when source is
877 // weak. Also, note, that we already checked linkage in LinkGlobals(),
878 // thus we assert here.
879 // FIXME: Should we weaken this assumption, 'dereference' alias and
880 // check for initializer of aliasee?
881 assert(SGV->isWeakForLinker());
888 // LinkFunctionProtos - Link the functions together between the two modules,
889 // without doing function bodies... this just adds external function prototypes
890 // to the Dest function...
892 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
893 ValueToValueMapTy &ValueMap,
895 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
897 // Loop over all of the functions in the src module, mapping them over
898 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
899 const Function *SF = I; // SrcFunction
900 GlobalValue *DGV = 0;
902 // Check to see if may have to link the function with the global, alias or
904 if (SF->hasName() && !SF->hasLocalLinkage())
905 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
907 // If we found a global with the same name in the dest module, but it has
908 // internal linkage, we are really not doing any linkage here.
909 if (DGV && DGV->hasLocalLinkage())
912 // If types don't agree due to opaque types, try to resolve them.
913 if (DGV && DGV->getType() != SF->getType())
914 RecursiveResolveTypes(SF->getType(), DGV->getType());
916 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
917 bool LinkFromSrc = false;
918 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
921 // If there is no linkage to be performed, just bring over SF without
924 // Function does not already exist, simply insert an function signature
925 // identical to SF into the dest module.
926 Function *NewDF = Function::Create(SF->getFunctionType(),
928 SF->getName(), Dest);
929 CopyGVAttributes(NewDF, SF);
931 // If the LLVM runtime renamed the function, but it is an externally
932 // visible symbol, DF must be an existing function with internal linkage.
934 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
935 ForceRenaming(NewDF, SF->getName());
937 // ... and remember this mapping...
938 ValueMap[SF] = NewDF;
942 // If the visibilities of the symbols disagree and the destination is a
943 // prototype, take the visibility of its input.
944 if (DGV->isDeclaration())
945 DGV->setVisibility(SF->getVisibility());
948 if (isa<GlobalAlias>(DGV))
949 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
950 "': symbol multiple defined");
952 // We have a definition of the same name but different type in the
953 // source module. Copy the prototype to the destination and replace
954 // uses of the destination's prototype with the new prototype.
955 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
956 SF->getName(), Dest);
957 CopyGVAttributes(NewDF, SF);
959 // Any uses of DF need to change to NewDF, with cast
960 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
963 // DF will conflict with NewDF because they both had the same. We must
964 // erase this now so ForceRenaming doesn't assert because DF might
965 // not have internal linkage.
966 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
967 Var->eraseFromParent();
969 cast<Function>(DGV)->eraseFromParent();
971 // If the symbol table renamed the function, but it is an externally
972 // visible symbol, DF must be an existing function with internal
973 // linkage. Rename it.
974 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
975 ForceRenaming(NewDF, SF->getName());
977 // Remember this mapping so uses in the source module get remapped
978 // later by MapValue.
979 ValueMap[SF] = NewDF;
983 // Not "link from source", keep the one in the DestModule and remap the
986 if (isa<GlobalAlias>(DGV)) {
987 // The only valid mappings are:
988 // - SF is external declaration, which is effectively a no-op.
989 // - SF is weak, when we just need to throw SF out.
990 if (!SF->isDeclaration() && !SF->isWeakForLinker())
991 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
992 "': symbol multiple defined");
995 // Set calculated linkage
996 DGV->setLinkage(NewLinkage);
998 // Make sure to remember this mapping.
999 ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
1004 // LinkFunctionBody - Copy the source function over into the dest function and
1005 // fix up references to values. At this point we know that Dest is an external
1006 // function, and that Src is not.
1007 static bool LinkFunctionBody(Function *Dest, Function *Src,
1008 ValueToValueMapTy &ValueMap,
1010 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1012 // Go through and convert function arguments over, remembering the mapping.
1013 Function::arg_iterator DI = Dest->arg_begin();
1014 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1015 I != E; ++I, ++DI) {
1016 DI->setName(I->getName()); // Copy the name information over...
1018 // Add a mapping to our local map
1022 // Splice the body of the source function into the dest function.
1023 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1025 // At this point, all of the instructions and values of the function are now
1026 // copied over. The only problem is that they are still referencing values in
1027 // the Source function as operands. Loop through all of the operands of the
1028 // functions and patch them up to point to the local versions...
1030 // This is the same as RemapInstruction, except that it avoids remapping
1031 // instruction and basic block operands.
1033 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1034 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1036 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1038 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1039 *OI = MapValue(*OI, ValueMap, true);
1041 // Remap attached metadata.
1042 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1043 I->getAllMetadata(MDs);
1044 for (SmallVectorImpl<std::pair<unsigned, MDNode *> >::iterator
1045 MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI) {
1046 Value *Old = MI->second;
1047 if (!isa<Instruction>(Old) && !isa<BasicBlock>(Old)) {
1048 Value *New = MapValue(Old, ValueMap, true);
1050 I->setMetadata(MI->first, cast<MDNode>(New));
1055 // There is no need to map the arguments anymore.
1056 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1064 // LinkFunctionBodies - Link in the function bodies that are defined in the
1065 // source module into the DestModule. This consists basically of copying the
1066 // function over and fixing up references to values.
1067 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1068 ValueToValueMapTy &ValueMap,
1071 // Loop over all of the functions in the src module, mapping them over as we
1073 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1074 if (!SF->isDeclaration()) { // No body if function is external
1075 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1077 // DF not external SF external?
1078 if (DF && DF->isDeclaration())
1079 // Only provide the function body if there isn't one already.
1080 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1087 // LinkAppendingVars - If there were any appending global variables, link them
1088 // together now. Return true on error.
1089 static bool LinkAppendingVars(Module *M,
1090 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1091 std::string *ErrorMsg) {
1092 if (AppendingVars.empty()) return false; // Nothing to do.
1094 // Loop over the multimap of appending vars, processing any variables with the
1095 // same name, forming a new appending global variable with both of the
1096 // initializers merged together, then rewrite references to the old variables
1098 std::vector<Constant*> Inits;
1099 while (AppendingVars.size() > 1) {
1100 // Get the first two elements in the map...
1101 std::multimap<std::string,
1102 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1104 // If the first two elements are for different names, there is no pair...
1105 // Otherwise there is a pair, so link them together...
1106 if (First->first == Second->first) {
1107 GlobalVariable *G1 = First->second, *G2 = Second->second;
1108 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1109 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1111 // Check to see that they two arrays agree on type...
1112 if (T1->getElementType() != T2->getElementType())
1113 return Error(ErrorMsg,
1114 "Appending variables with different element types need to be linked!");
1115 if (G1->isConstant() != G2->isConstant())
1116 return Error(ErrorMsg,
1117 "Appending variables linked with different const'ness!");
1119 if (G1->getAlignment() != G2->getAlignment())
1120 return Error(ErrorMsg,
1121 "Appending variables with different alignment need to be linked!");
1123 if (G1->getVisibility() != G2->getVisibility())
1124 return Error(ErrorMsg,
1125 "Appending variables with different visibility need to be linked!");
1127 if (G1->getSection() != G2->getSection())
1128 return Error(ErrorMsg,
1129 "Appending variables with different section name need to be linked!");
1131 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1132 ArrayType *NewType = ArrayType::get(T1->getElementType(),
1135 G1->setName(""); // Clear G1's name in case of a conflict!
1137 // Create the new global variable...
1138 GlobalVariable *NG =
1139 new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1140 /*init*/0, First->first, 0, G1->isThreadLocal(),
1141 G1->getType()->getAddressSpace());
1143 // Propagate alignment, visibility and section info.
1144 CopyGVAttributes(NG, G1);
1146 // Merge the initializer...
1147 Inits.reserve(NewSize);
1148 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1149 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1150 Inits.push_back(I->getOperand(i));
1152 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1153 Constant *CV = Constant::getNullValue(T1->getElementType());
1154 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1155 Inits.push_back(CV);
1157 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1158 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1159 Inits.push_back(I->getOperand(i));
1161 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1162 Constant *CV = Constant::getNullValue(T2->getElementType());
1163 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1164 Inits.push_back(CV);
1166 NG->setInitializer(ConstantArray::get(NewType, Inits));
1169 // Replace any uses of the two global variables with uses of the new
1172 // FIXME: This should rewrite simple/straight-forward uses such as
1173 // getelementptr instructions to not use the Cast!
1174 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1176 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1179 // Remove the two globals from the module now...
1180 M->getGlobalList().erase(G1);
1181 M->getGlobalList().erase(G2);
1183 // Put the new global into the AppendingVars map so that we can handle
1184 // linking of more than two vars...
1185 Second->second = NG;
1187 AppendingVars.erase(First);
1193 static bool ResolveAliases(Module *Dest) {
1194 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1196 // We can't sue resolveGlobalAlias here because we need to preserve
1197 // bitcasts and GEPs.
1198 if (const Constant *C = I->getAliasee()) {
1199 while (dyn_cast<GlobalAlias>(C))
1200 C = cast<GlobalAlias>(C)->getAliasee();
1201 const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1202 if (C != I && !(GV && GV->isDeclaration()))
1203 I->replaceAllUsesWith(const_cast<Constant*>(C));
1209 // LinkModules - This function links two modules together, with the resulting
1210 // left module modified to be the composite of the two input modules. If an
1211 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1212 // the problem. Upon failure, the Dest module could be in a modified state, and
1213 // shouldn't be relied on to be consistent.
1215 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1216 assert(Dest != 0 && "Invalid Destination module");
1217 assert(Src != 0 && "Invalid Source Module");
1219 if (Dest->getDataLayout().empty()) {
1220 if (!Src->getDataLayout().empty()) {
1221 Dest->setDataLayout(Src->getDataLayout());
1223 std::string DataLayout;
1225 if (Dest->getEndianness() == Module::AnyEndianness) {
1226 if (Src->getEndianness() == Module::BigEndian)
1227 DataLayout.append("E");
1228 else if (Src->getEndianness() == Module::LittleEndian)
1229 DataLayout.append("e");
1232 if (Dest->getPointerSize() == Module::AnyPointerSize) {
1233 if (Src->getPointerSize() == Module::Pointer64)
1234 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1235 else if (Src->getPointerSize() == Module::Pointer32)
1236 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1238 Dest->setDataLayout(DataLayout);
1242 // Copy the target triple from the source to dest if the dest's is empty.
1243 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1244 Dest->setTargetTriple(Src->getTargetTriple());
1246 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1247 Src->getDataLayout() != Dest->getDataLayout())
1248 errs() << "WARNING: Linking two modules of different data layouts!\n";
1249 if (!Src->getTargetTriple().empty() &&
1250 Dest->getTargetTriple() != Src->getTargetTriple())
1251 errs() << "WARNING: Linking two modules of different target triples!\n";
1253 // Append the module inline asm string.
1254 if (!Src->getModuleInlineAsm().empty()) {
1255 if (Dest->getModuleInlineAsm().empty())
1256 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1258 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1259 Src->getModuleInlineAsm());
1262 // Update the destination module's dependent libraries list with the libraries
1263 // from the source module. There's no opportunity for duplicates here as the
1264 // Module ensures that duplicate insertions are discarded.
1265 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1267 Dest->addLibrary(*SI);
1269 // LinkTypes - Go through the symbol table of the Src module and see if any
1270 // types are named in the src module that are not named in the Dst module.
1271 // Make sure there are no type name conflicts.
1272 if (LinkTypes(Dest, Src, ErrorMsg))
1275 // ValueMap - Mapping of values from what they used to be in Src, to what they
1276 // are now in Dest. ValueToValueMapTy is a ValueMap, which involves some
1277 // overhead due to the use of Value handles which the Linker doesn't actually
1278 // need, but this allows us to reuse the ValueMapper code.
1279 ValueToValueMapTy ValueMap;
1281 // AppendingVars - Keep track of global variables in the destination module
1282 // with appending linkage. After the module is linked together, they are
1283 // appended and the module is rewritten.
1284 std::multimap<std::string, GlobalVariable *> AppendingVars;
1285 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1287 // Add all of the appending globals already in the Dest module to
1289 if (I->hasAppendingLinkage())
1290 AppendingVars.insert(std::make_pair(I->getName(), I));
1293 // Insert all of the globals in src into the Dest module... without linking
1294 // initializers (which could refer to functions not yet mapped over).
1295 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1298 // Link the functions together between the two modules, without doing function
1299 // bodies... this just adds external function prototypes to the Dest
1300 // function... We do this so that when we begin processing function bodies,
1301 // all of the global values that may be referenced are available in our
1303 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1306 // If there were any alias, link them now. We really need to do this now,
1307 // because all of the aliases that may be referenced need to be available in
1309 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1311 // Update the initializers in the Dest module now that all globals that may
1312 // be referenced are in Dest.
1313 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1315 // Link in the function bodies that are defined in the source module into the
1316 // DestModule. This consists basically of copying the function over and
1317 // fixing up references to values.
1318 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1320 // If there were any appending global variables, link them together now.
1321 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1323 // Resolve all uses of aliases with aliasees
1324 if (ResolveAliases(Dest)) return true;
1326 // Remap all of the named mdnoes in Src into the Dest module. We do this
1327 // after linking GlobalValues so that MDNodes that reference GlobalValues
1328 // are properly remapped.
1329 LinkNamedMDNodes(Dest, Src, ValueMap);
1331 // If the source library's module id is in the dependent library list of the
1332 // destination library, remove it since that module is now linked in.
1334 modId.set(Src->getModuleIdentifier());
1335 if (!modId.isEmpty())
1336 Dest->removeLibrary(modId.getBasename());