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/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/Support/Streams.h"
29 #include "llvm/System/Path.h"
30 #include "llvm/ADT/DenseMap.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 std::string &Message) {
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 /// erase - Remove the specified type, returning true if it was in the set.
99 bool erase(const Type *Ty) {
100 if (!TheMap.erase(Ty))
102 if (Ty->isAbstract())
103 Ty->removeAbstractTypeUser(this);
107 /// insert - This returns true if the pointer was new to the set, false if it
108 /// was already in the set.
109 bool insert(const Type *Src, const Type *Dst) {
110 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
111 return false; // Already in map.
112 if (Src->isAbstract())
113 Src->addAbstractTypeUser(this);
118 /// refineAbstractType - The callback method invoked when an abstract type is
119 /// resolved to another type. An object must override this method to update
120 /// its internal state to reference NewType instead of OldType.
122 virtual void refineAbstractType(const DerivedType *OldTy,
124 TheMapTy::iterator I = TheMap.find(OldTy);
125 const Type *DstTy = I->second;
128 if (OldTy->isAbstract())
129 OldTy->removeAbstractTypeUser(this);
131 // Don't reinsert into the map if the key is concrete now.
132 if (NewTy->isAbstract())
133 insert(NewTy, DstTy);
136 /// The other case which AbstractTypeUsers must be aware of is when a type
137 /// makes the transition from being abstract (where it has clients on it's
138 /// AbstractTypeUsers list) to concrete (where it does not). This method
139 /// notifies ATU's when this occurs for a type.
140 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
142 AbsTy->removeAbstractTypeUser(this);
146 virtual void dump() const {
147 cerr << "AbstractTypeSet!\n";
153 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
154 // recurses down into derived types, merging the used types if the parent types
156 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
157 LinkerTypeMap &Pointers) {
158 if (DstTy == SrcTy) return false; // If already equal, noop
160 // If we found our opaque type, resolve it now!
161 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
162 return ResolveTypes(DstTy, SrcTy);
164 // Two types cannot be resolved together if they are of different primitive
165 // type. For example, we cannot resolve an int to a float.
166 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
168 // If neither type is abstract, then they really are just different types.
169 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
172 // Otherwise, resolve the used type used by this derived type...
173 switch (DstTy->getTypeID()) {
176 case Type::FunctionTyID: {
177 const FunctionType *DstFT = cast<FunctionType>(DstTy);
178 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
179 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
180 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
183 // Use TypeHolder's so recursive resolution won't break us.
184 PATypeHolder ST(SrcFT), DT(DstFT);
185 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
186 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
187 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
192 case Type::StructTyID: {
193 const StructType *DstST = cast<StructType>(DstTy);
194 const StructType *SrcST = cast<StructType>(SrcTy);
195 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
198 PATypeHolder ST(SrcST), DT(DstST);
199 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
200 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
201 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
206 case Type::ArrayTyID: {
207 const ArrayType *DAT = cast<ArrayType>(DstTy);
208 const ArrayType *SAT = cast<ArrayType>(SrcTy);
209 if (DAT->getNumElements() != SAT->getNumElements()) return true;
210 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
213 case Type::VectorTyID: {
214 const VectorType *DVT = cast<VectorType>(DstTy);
215 const VectorType *SVT = cast<VectorType>(SrcTy);
216 if (DVT->getNumElements() != SVT->getNumElements()) return true;
217 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
220 case Type::PointerTyID: {
221 const PointerType *DstPT = cast<PointerType>(DstTy);
222 const PointerType *SrcPT = cast<PointerType>(SrcTy);
224 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
227 // If this is a pointer type, check to see if we have already seen it. If
228 // so, we are in a recursive branch. Cut off the search now. We cannot use
229 // an associative container for this search, because the type pointers (keys
230 // in the container) change whenever types get resolved.
231 if (SrcPT->isAbstract())
232 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
233 return ExistingDestTy != DstPT;
235 if (DstPT->isAbstract())
236 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
237 return ExistingSrcTy != SrcPT;
238 // Otherwise, add the current pointers to the vector to stop recursion on
240 if (DstPT->isAbstract())
241 Pointers.insert(DstPT, SrcPT);
242 if (SrcPT->isAbstract())
243 Pointers.insert(SrcPT, DstPT);
245 return RecursiveResolveTypesI(DstPT->getElementType(),
246 SrcPT->getElementType(), Pointers);
251 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
252 LinkerTypeMap PointerTypes;
253 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
257 // LinkTypes - Go through the symbol table of the Src module and see if any
258 // types are named in the src module that are not named in the Dst module.
259 // Make sure there are no type name conflicts.
260 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
261 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
262 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
264 // Look for a type plane for Type's...
265 TypeSymbolTable::const_iterator TI = SrcST->begin();
266 TypeSymbolTable::const_iterator TE = SrcST->end();
267 if (TI == TE) return false; // No named types, do nothing.
269 // Some types cannot be resolved immediately because they depend on other
270 // types being resolved to each other first. This contains a list of types we
271 // are waiting to recheck.
272 std::vector<std::string> DelayedTypesToResolve;
274 for ( ; TI != TE; ++TI ) {
275 const std::string &Name = TI->first;
276 const Type *RHS = TI->second;
278 // Check to see if this type name is already in the dest module.
279 Type *Entry = DestST->lookup(Name);
281 // If the name is just in the source module, bring it over to the dest.
284 DestST->insert(Name, const_cast<Type*>(RHS));
285 } else if (ResolveTypes(Entry, RHS)) {
286 // They look different, save the types 'till later to resolve.
287 DelayedTypesToResolve.push_back(Name);
291 // Iteratively resolve types while we can...
292 while (!DelayedTypesToResolve.empty()) {
293 // Loop over all of the types, attempting to resolve them if possible...
294 unsigned OldSize = DelayedTypesToResolve.size();
296 // Try direct resolution by name...
297 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
298 const std::string &Name = DelayedTypesToResolve[i];
299 Type *T1 = SrcST->lookup(Name);
300 Type *T2 = DestST->lookup(Name);
301 if (!ResolveTypes(T2, T1)) {
302 // We are making progress!
303 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
308 // Did we not eliminate any types?
309 if (DelayedTypesToResolve.size() == OldSize) {
310 // Attempt to resolve subelements of types. This allows us to merge these
311 // two types: { int* } and { opaque* }
312 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
313 const std::string &Name = DelayedTypesToResolve[i];
314 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
315 // We are making progress!
316 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
318 // Go back to the main loop, perhaps we can resolve directly by name
324 // If we STILL cannot resolve the types, then there is something wrong.
325 if (DelayedTypesToResolve.size() == OldSize) {
326 // Remove the symbol name from the destination.
327 DelayedTypesToResolve.pop_back();
337 static void PrintMap(const std::map<const Value*, Value*> &M) {
338 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
340 cerr << " Fr: " << (void*)I->first << " ";
342 cerr << " To: " << (void*)I->second << " ";
350 // RemapOperand - Use ValueMap to convert constants from one module to another.
351 static Value *RemapOperand(const Value *In,
352 std::map<const Value*, Value*> &ValueMap,
353 LLVMContext &Context) {
354 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
355 if (I != ValueMap.end())
358 // Check to see if it's a constant that we are interested in transforming.
360 if (const Constant *CPV = dyn_cast<Constant>(In)) {
361 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
362 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
363 return const_cast<Constant*>(CPV); // Simple constants stay identical.
365 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
366 std::vector<Constant*> Operands(CPA->getNumOperands());
367 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
368 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap,
371 Context.getConstantArray(cast<ArrayType>(CPA->getType()), Operands);
372 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
373 std::vector<Constant*> Operands(CPS->getNumOperands());
374 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
375 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap,
378 Context.getConstantStruct(cast<StructType>(CPS->getType()), Operands);
379 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
380 Result = const_cast<Constant*>(CPV);
381 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
382 std::vector<Constant*> Operands(CP->getNumOperands());
383 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
384 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap,
386 Result = Context.getConstantVector(Operands);
387 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
388 std::vector<Constant*> Ops;
389 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
390 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap,
392 Result = CE->getWithOperands(Ops);
394 assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
395 assert(0 && "Unknown type of derived type constant value!");
397 } else if (isa<InlineAsm>(In)) {
398 Result = const_cast<Value*>(In);
401 // Cache the mapping in our local map structure
403 ValueMap[In] = Result;
408 cerr << "LinkModules ValueMap: \n";
411 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
412 assert(0 && "Couldn't remap value!");
417 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
418 /// in the symbol table. This is good for all clients except for us. Go
419 /// through the trouble to force this back.
420 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
421 assert(GV->getName() != Name && "Can't force rename to self");
422 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
424 // If there is a conflict, rename the conflict.
425 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
426 assert(ConflictGV->hasLocalLinkage() &&
427 "Not conflicting with a static global, should link instead!");
428 GV->takeName(ConflictGV);
429 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
430 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
432 GV->setName(Name); // Force the name back
436 /// CopyGVAttributes - copy additional attributes (those not needed to construct
437 /// a GlobalValue) from the SrcGV to the DestGV.
438 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
439 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
440 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
441 DestGV->copyAttributesFrom(SrcGV);
442 DestGV->setAlignment(Alignment);
445 /// GetLinkageResult - This analyzes the two global values and determines what
446 /// the result will look like in the destination module. In particular, it
447 /// computes the resultant linkage type, computes whether the global in the
448 /// source should be copied over to the destination (replacing the existing
449 /// one), and computes whether this linkage is an error or not. It also performs
450 /// visibility checks: we cannot link together two symbols with different
452 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
453 GlobalValue::LinkageTypes <, bool &LinkFromSrc,
455 assert((!Dest || !Src->hasLocalLinkage()) &&
456 "If Src has internal linkage, Dest shouldn't be set!");
458 // Linking something to nothing.
460 LT = Src->getLinkage();
461 } else if (Src->isDeclaration()) {
462 // If Src is external or if both Src & Dest are external.. Just link the
463 // external globals, we aren't adding anything.
464 if (Src->hasDLLImportLinkage()) {
465 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
466 if (Dest->isDeclaration()) {
468 LT = Src->getLinkage();
470 } else if (Dest->hasExternalWeakLinkage()) {
471 // If the Dest is weak, use the source linkage.
473 LT = Src->getLinkage();
476 LT = Dest->getLinkage();
478 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
479 // If Dest is external but Src is not:
481 LT = Src->getLinkage();
482 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
483 if (Src->getLinkage() != Dest->getLinkage())
484 return Error(Err, "Linking globals named '" + Src->getName() +
485 "': can only link appending global with another appending global!");
486 LinkFromSrc = true; // Special cased.
487 LT = Src->getLinkage();
488 } else if (Src->isWeakForLinker()) {
489 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
491 if (Dest->hasExternalWeakLinkage() ||
492 Dest->hasAvailableExternallyLinkage() ||
493 (Dest->hasLinkOnceLinkage() &&
494 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
496 LT = Src->getLinkage();
499 LT = Dest->getLinkage();
501 } else if (Dest->isWeakForLinker()) {
502 // At this point we know that Src has External* or DLL* linkage.
503 if (Src->hasExternalWeakLinkage()) {
505 LT = Dest->getLinkage();
508 LT = GlobalValue::ExternalLinkage;
511 assert((Dest->hasExternalLinkage() ||
512 Dest->hasDLLImportLinkage() ||
513 Dest->hasDLLExportLinkage() ||
514 Dest->hasExternalWeakLinkage()) &&
515 (Src->hasExternalLinkage() ||
516 Src->hasDLLImportLinkage() ||
517 Src->hasDLLExportLinkage() ||
518 Src->hasExternalWeakLinkage()) &&
519 "Unexpected linkage type!");
520 return Error(Err, "Linking globals named '" + Src->getName() +
521 "': symbol multiply defined!");
525 if (Dest && Src->getVisibility() != Dest->getVisibility())
526 if (!Src->isDeclaration() && !Dest->isDeclaration())
527 return Error(Err, "Linking globals named '" + Src->getName() +
528 "': symbols have different visibilities!");
532 // LinkGlobals - Loop through the global variables in the src module and merge
533 // them into the dest module.
534 static bool LinkGlobals(Module *Dest, const Module *Src,
535 std::map<const Value*, Value*> &ValueMap,
536 std::multimap<std::string, GlobalVariable *> &AppendingVars,
538 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
539 LLVMContext &Context = Dest->getContext();
541 // Loop over all of the globals in the src module, mapping them over as we go
542 for (Module::const_global_iterator I = Src->global_begin(),
543 E = Src->global_end(); I != E; ++I) {
544 const GlobalVariable *SGV = I;
545 GlobalValue *DGV = 0;
547 // Check to see if may have to link the global with the global, alias or
549 if (SGV->hasName() && !SGV->hasLocalLinkage())
550 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getNameStart(),
553 // If we found a global with the same name in the dest module, but it has
554 // internal linkage, we are really not doing any linkage here.
555 if (DGV && DGV->hasLocalLinkage())
558 // If types don't agree due to opaque types, try to resolve them.
559 if (DGV && DGV->getType() != SGV->getType())
560 RecursiveResolveTypes(SGV->getType(), DGV->getType());
562 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
563 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
564 "Global must either be external or have an initializer!");
566 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
567 bool LinkFromSrc = false;
568 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
572 // No linking to be performed, simply create an identical version of the
573 // symbol over in the dest module... the initializer will be filled in
574 // later by LinkGlobalInits.
575 GlobalVariable *NewDGV =
576 new GlobalVariable(SGV->getType()->getElementType(),
577 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
578 SGV->getName(), Dest, false,
579 SGV->getType()->getAddressSpace());
580 // Propagate alignment, visibility and section info.
581 CopyGVAttributes(NewDGV, SGV);
583 // If the LLVM runtime renamed the global, but it is an externally visible
584 // symbol, DGV must be an existing global with internal linkage. Rename
586 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
587 ForceRenaming(NewDGV, SGV->getName());
589 // Make sure to remember this mapping.
590 ValueMap[SGV] = NewDGV;
592 // Keep track that this is an appending variable.
593 if (SGV->hasAppendingLinkage())
594 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
598 // If the visibilities of the symbols disagree and the destination is a
599 // prototype, take the visibility of its input.
600 if (DGV->isDeclaration())
601 DGV->setVisibility(SGV->getVisibility());
603 if (DGV->hasAppendingLinkage()) {
604 // No linking is performed yet. Just insert a new copy of the global, and
605 // keep track of the fact that it is an appending variable in the
606 // AppendingVars map. The name is cleared out so that no linkage is
608 GlobalVariable *NewDGV =
609 new GlobalVariable(SGV->getType()->getElementType(),
610 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
612 SGV->getType()->getAddressSpace());
614 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
615 NewDGV->setAlignment(DGV->getAlignment());
616 // Propagate alignment, section and visibility info.
617 CopyGVAttributes(NewDGV, SGV);
619 // Make sure to remember this mapping...
620 ValueMap[SGV] = NewDGV;
622 // Keep track that this is an appending variable...
623 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
628 if (isa<GlobalAlias>(DGV))
629 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
630 "': symbol multiple defined");
632 // If the types don't match, and if we are to link from the source, nuke
633 // DGV and create a new one of the appropriate type. Note that the thing
634 // we are replacing may be a function (if a prototype, weak, etc) or a
636 GlobalVariable *NewDGV =
637 new GlobalVariable(SGV->getType()->getElementType(), SGV->isConstant(),
638 NewLinkage, /*init*/0, DGV->getName(), Dest, false,
639 SGV->getType()->getAddressSpace());
641 // Propagate alignment, section, and visibility info.
642 CopyGVAttributes(NewDGV, SGV);
643 DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDGV,
646 // DGV will conflict with NewDGV because they both had the same
647 // name. We must erase this now so ForceRenaming doesn't assert
648 // because DGV might not have internal linkage.
649 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
650 Var->eraseFromParent();
652 cast<Function>(DGV)->eraseFromParent();
655 // If the symbol table renamed the global, but it is an externally visible
656 // symbol, DGV must be an existing global with internal linkage. Rename.
657 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
658 ForceRenaming(NewDGV, SGV->getName());
660 // Inherit const as appropriate.
661 NewDGV->setConstant(SGV->isConstant());
663 // Make sure to remember this mapping.
664 ValueMap[SGV] = NewDGV;
668 // Not "link from source", keep the one in the DestModule and remap the
671 // Special case for const propagation.
672 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
673 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
674 DGVar->setConstant(true);
676 // SGV is global, but DGV is alias.
677 if (isa<GlobalAlias>(DGV)) {
678 // The only valid mappings are:
679 // - SGV is external declaration, which is effectively a no-op.
680 // - SGV is weak, when we just need to throw SGV out.
681 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
682 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
683 "': symbol multiple defined");
686 // Set calculated linkage
687 DGV->setLinkage(NewLinkage);
689 // Make sure to remember this mapping...
690 ValueMap[SGV] = Context.getConstantExprBitCast(DGV, SGV->getType());
695 static GlobalValue::LinkageTypes
696 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
697 GlobalValue::LinkageTypes SL = SGV->getLinkage();
698 GlobalValue::LinkageTypes DL = DGV->getLinkage();
699 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
700 return GlobalValue::ExternalLinkage;
701 else if (SL == GlobalValue::WeakAnyLinkage ||
702 DL == GlobalValue::WeakAnyLinkage)
703 return GlobalValue::WeakAnyLinkage;
704 else if (SL == GlobalValue::WeakODRLinkage ||
705 DL == GlobalValue::WeakODRLinkage)
706 return GlobalValue::WeakODRLinkage;
707 else if (SL == GlobalValue::InternalLinkage &&
708 DL == GlobalValue::InternalLinkage)
709 return GlobalValue::InternalLinkage;
711 assert (SL == GlobalValue::PrivateLinkage &&
712 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
713 return GlobalValue::PrivateLinkage;
717 // LinkAlias - Loop through the alias in the src module and link them into the
718 // dest module. We're assuming, that all functions/global variables were already
720 static bool LinkAlias(Module *Dest, const Module *Src,
721 std::map<const Value*, Value*> &ValueMap,
723 LLVMContext &Context = Dest->getContext();
725 // Loop over all alias in the src module
726 for (Module::const_alias_iterator I = Src->alias_begin(),
727 E = Src->alias_end(); I != E; ++I) {
728 const GlobalAlias *SGA = I;
729 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
730 GlobalAlias *NewGA = NULL;
732 // Globals were already linked, thus we can just query ValueMap for variant
733 // of SAliasee in Dest.
734 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
735 assert(VMI != ValueMap.end() && "Aliasee not linked");
736 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
737 GlobalValue* DGV = NULL;
739 // Try to find something 'similar' to SGA in destination module.
740 if (!DGV && !SGA->hasLocalLinkage()) {
741 DGV = Dest->getNamedAlias(SGA->getName());
743 // If types don't agree due to opaque types, try to resolve them.
744 if (DGV && DGV->getType() != SGA->getType())
745 RecursiveResolveTypes(SGA->getType(), DGV->getType());
748 if (!DGV && !SGA->hasLocalLinkage()) {
749 DGV = Dest->getGlobalVariable(SGA->getName());
751 // If types don't agree due to opaque types, try to resolve them.
752 if (DGV && DGV->getType() != SGA->getType())
753 RecursiveResolveTypes(SGA->getType(), DGV->getType());
756 if (!DGV && !SGA->hasLocalLinkage()) {
757 DGV = Dest->getFunction(SGA->getName());
759 // If types don't agree due to opaque types, try to resolve them.
760 if (DGV && DGV->getType() != SGA->getType())
761 RecursiveResolveTypes(SGA->getType(), DGV->getType());
764 // No linking to be performed on internal stuff.
765 if (DGV && DGV->hasLocalLinkage())
768 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
769 // Types are known to be the same, check whether aliasees equal. As
770 // globals are already linked we just need query ValueMap to find the
772 if (DAliasee == DGA->getAliasedGlobal()) {
773 // This is just two copies of the same alias. Propagate linkage, if
775 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
778 // Proceed to 'common' steps
780 return Error(Err, "Alias Collision on '" + SGA->getName()+
781 "': aliases have different aliasees");
782 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
783 // The only allowed way is to link alias with external declaration or weak
785 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
786 // But only if aliasee is global too...
787 if (!isa<GlobalVariable>(DAliasee))
788 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
789 "': aliasee is not global variable");
791 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
792 SGA->getName(), DAliasee, Dest);
793 CopyGVAttributes(NewGA, SGA);
795 // Any uses of DGV need to change to NewGA, with cast, if needed.
796 if (SGA->getType() != DGVar->getType())
797 DGVar->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
800 DGVar->replaceAllUsesWith(NewGA);
802 // DGVar will conflict with NewGA because they both had the same
803 // name. We must erase this now so ForceRenaming doesn't assert
804 // because DGV might not have internal linkage.
805 DGVar->eraseFromParent();
807 // Proceed to 'common' steps
809 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
810 "': symbol multiple defined");
811 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
812 // The only allowed way is to link alias with external declaration or weak
814 if (DF->isDeclaration() || DF->isWeakForLinker()) {
815 // But only if aliasee is function too...
816 if (!isa<Function>(DAliasee))
817 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
818 "': aliasee is not function");
820 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
821 SGA->getName(), DAliasee, Dest);
822 CopyGVAttributes(NewGA, SGA);
824 // Any uses of DF need to change to NewGA, with cast, if needed.
825 if (SGA->getType() != DF->getType())
826 DF->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
829 DF->replaceAllUsesWith(NewGA);
831 // DF will conflict with NewGA because they both had the same
832 // name. We must erase this now so ForceRenaming doesn't assert
833 // because DF might not have internal linkage.
834 DF->eraseFromParent();
836 // Proceed to 'common' steps
838 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
839 "': symbol multiple defined");
841 // No linking to be performed, simply create an identical version of the
842 // alias over in the dest module...
844 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
845 SGA->getName(), DAliasee, Dest);
846 CopyGVAttributes(NewGA, SGA);
848 // Proceed to 'common' steps
851 assert(NewGA && "No alias was created in destination module!");
853 // If the symbol table renamed the alias, but it is an externally visible
854 // symbol, DGA must be an global value with internal linkage. Rename it.
855 if (NewGA->getName() != SGA->getName() &&
856 !NewGA->hasLocalLinkage())
857 ForceRenaming(NewGA, SGA->getName());
859 // Remember this mapping so uses in the source module get remapped
860 // later by RemapOperand.
861 ValueMap[SGA] = NewGA;
868 // LinkGlobalInits - Update the initializers in the Dest module now that all
869 // globals that may be referenced are in Dest.
870 static bool LinkGlobalInits(Module *Dest, const Module *Src,
871 std::map<const Value*, Value*> &ValueMap,
873 // Loop over all of the globals in the src module, mapping them over as we go
874 for (Module::const_global_iterator I = Src->global_begin(),
875 E = Src->global_end(); I != E; ++I) {
876 const GlobalVariable *SGV = I;
878 if (SGV->hasInitializer()) { // Only process initialized GV's
879 // Figure out what the initializer looks like in the dest module...
881 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap,
882 Dest->getContext()));
883 // Grab destination global variable or alias.
884 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
886 // If dest if global variable, check that initializers match.
887 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
888 if (DGVar->hasInitializer()) {
889 if (SGV->hasExternalLinkage()) {
890 if (DGVar->getInitializer() != SInit)
891 return Error(Err, "Global Variable Collision on '" +
893 "': global variables have different initializers");
894 } else if (DGVar->isWeakForLinker()) {
895 // Nothing is required, mapped values will take the new global
897 } else if (SGV->isWeakForLinker()) {
898 // Nothing is required, mapped values will take the new global
900 } else if (DGVar->hasAppendingLinkage()) {
901 assert(0 && "Appending linkage unimplemented!");
903 assert(0 && "Unknown linkage!");
906 // Copy the initializer over now...
907 DGVar->setInitializer(SInit);
910 // Destination is alias, the only valid situation is when source is
911 // weak. Also, note, that we already checked linkage in LinkGlobals(),
912 // thus we assert here.
913 // FIXME: Should we weaken this assumption, 'dereference' alias and
914 // check for initializer of aliasee?
915 assert(SGV->isWeakForLinker());
922 // LinkFunctionProtos - Link the functions together between the two modules,
923 // without doing function bodies... this just adds external function prototypes
924 // to the Dest function...
926 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
927 std::map<const Value*, Value*> &ValueMap,
929 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
930 LLVMContext &Context = Dest->getContext();
932 // Loop over all of the functions in the src module, mapping them over
933 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
934 const Function *SF = I; // SrcFunction
935 GlobalValue *DGV = 0;
937 // Check to see if may have to link the function with the global, alias or
939 if (SF->hasName() && !SF->hasLocalLinkage())
940 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getNameStart(),
943 // If we found a global with the same name in the dest module, but it has
944 // internal linkage, we are really not doing any linkage here.
945 if (DGV && DGV->hasLocalLinkage())
948 // If types don't agree due to opaque types, try to resolve them.
949 if (DGV && DGV->getType() != SF->getType())
950 RecursiveResolveTypes(SF->getType(), DGV->getType());
952 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
953 bool LinkFromSrc = false;
954 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
957 // If there is no linkage to be performed, just bring over SF without
960 // Function does not already exist, simply insert an function signature
961 // identical to SF into the dest module.
962 Function *NewDF = Function::Create(SF->getFunctionType(),
964 SF->getName(), Dest);
965 CopyGVAttributes(NewDF, SF);
967 // If the LLVM runtime renamed the function, but it is an externally
968 // visible symbol, DF must be an existing function with internal linkage.
970 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
971 ForceRenaming(NewDF, SF->getName());
973 // ... and remember this mapping...
974 ValueMap[SF] = NewDF;
978 // If the visibilities of the symbols disagree and the destination is a
979 // prototype, take the visibility of its input.
980 if (DGV->isDeclaration())
981 DGV->setVisibility(SF->getVisibility());
984 if (isa<GlobalAlias>(DGV))
985 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
986 "': symbol multiple defined");
988 // We have a definition of the same name but different type in the
989 // source module. Copy the prototype to the destination and replace
990 // uses of the destination's prototype with the new prototype.
991 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
992 SF->getName(), Dest);
993 CopyGVAttributes(NewDF, SF);
995 // Any uses of DF need to change to NewDF, with cast
996 DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDF,
999 // DF will conflict with NewDF because they both had the same. We must
1000 // erase this now so ForceRenaming doesn't assert because DF might
1001 // not have internal linkage.
1002 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1003 Var->eraseFromParent();
1005 cast<Function>(DGV)->eraseFromParent();
1007 // If the symbol table renamed the function, but it is an externally
1008 // visible symbol, DF must be an existing function with internal
1009 // linkage. Rename it.
1010 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
1011 ForceRenaming(NewDF, SF->getName());
1013 // Remember this mapping so uses in the source module get remapped
1014 // later by RemapOperand.
1015 ValueMap[SF] = NewDF;
1019 // Not "link from source", keep the one in the DestModule and remap the
1022 if (isa<GlobalAlias>(DGV)) {
1023 // The only valid mappings are:
1024 // - SF is external declaration, which is effectively a no-op.
1025 // - SF is weak, when we just need to throw SF out.
1026 if (!SF->isDeclaration() && !SF->isWeakForLinker())
1027 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1028 "': symbol multiple defined");
1031 // Set calculated linkage
1032 DGV->setLinkage(NewLinkage);
1034 // Make sure to remember this mapping.
1035 ValueMap[SF] = Context.getConstantExprBitCast(DGV, SF->getType());
1040 // LinkFunctionBody - Copy the source function over into the dest function and
1041 // fix up references to values. At this point we know that Dest is an external
1042 // function, and that Src is not.
1043 static bool LinkFunctionBody(Function *Dest, Function *Src,
1044 std::map<const Value*, Value*> &ValueMap,
1046 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1048 // Go through and convert function arguments over, remembering the mapping.
1049 Function::arg_iterator DI = Dest->arg_begin();
1050 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1051 I != E; ++I, ++DI) {
1052 DI->setName(I->getName()); // Copy the name information over...
1054 // Add a mapping to our local map
1058 // Splice the body of the source function into the dest function.
1059 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1061 // At this point, all of the instructions and values of the function are now
1062 // copied over. The only problem is that they are still referencing values in
1063 // the Source function as operands. Loop through all of the operands of the
1064 // functions and patch them up to point to the local versions...
1066 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1067 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1068 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1070 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1071 *OI = RemapOperand(*OI, ValueMap, *Dest->getContext());
1073 // There is no need to map the arguments anymore.
1074 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1082 // LinkFunctionBodies - Link in the function bodies that are defined in the
1083 // source module into the DestModule. This consists basically of copying the
1084 // function over and fixing up references to values.
1085 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1086 std::map<const Value*, Value*> &ValueMap,
1089 // Loop over all of the functions in the src module, mapping them over as we
1091 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1092 if (!SF->isDeclaration()) { // No body if function is external
1093 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1095 // DF not external SF external?
1096 if (DF && DF->isDeclaration())
1097 // Only provide the function body if there isn't one already.
1098 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1105 // LinkAppendingVars - If there were any appending global variables, link them
1106 // together now. Return true on error.
1107 static bool LinkAppendingVars(Module *M,
1108 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1109 std::string *ErrorMsg) {
1110 if (AppendingVars.empty()) return false; // Nothing to do.
1112 LLVMContext &Context = M->getContext();
1114 // Loop over the multimap of appending vars, processing any variables with the
1115 // same name, forming a new appending global variable with both of the
1116 // initializers merged together, then rewrite references to the old variables
1118 std::vector<Constant*> Inits;
1119 while (AppendingVars.size() > 1) {
1120 // Get the first two elements in the map...
1121 std::multimap<std::string,
1122 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1124 // If the first two elements are for different names, there is no pair...
1125 // Otherwise there is a pair, so link them together...
1126 if (First->first == Second->first) {
1127 GlobalVariable *G1 = First->second, *G2 = Second->second;
1128 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1129 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1131 // Check to see that they two arrays agree on type...
1132 if (T1->getElementType() != T2->getElementType())
1133 return Error(ErrorMsg,
1134 "Appending variables with different element types need to be linked!");
1135 if (G1->isConstant() != G2->isConstant())
1136 return Error(ErrorMsg,
1137 "Appending variables linked with different const'ness!");
1139 if (G1->getAlignment() != G2->getAlignment())
1140 return Error(ErrorMsg,
1141 "Appending variables with different alignment need to be linked!");
1143 if (G1->getVisibility() != G2->getVisibility())
1144 return Error(ErrorMsg,
1145 "Appending variables with different visibility need to be linked!");
1147 if (G1->getSection() != G2->getSection())
1148 return Error(ErrorMsg,
1149 "Appending variables with different section name need to be linked!");
1151 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1152 ArrayType *NewType = Context.getArrayType(T1->getElementType(),
1155 G1->setName(""); // Clear G1's name in case of a conflict!
1157 // Create the new global variable...
1158 GlobalVariable *NG =
1159 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
1160 /*init*/0, First->first, M, G1->isThreadLocal(),
1161 G1->getType()->getAddressSpace());
1163 // Propagate alignment, visibility and section info.
1164 CopyGVAttributes(NG, G1);
1166 // Merge the initializer...
1167 Inits.reserve(NewSize);
1168 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1169 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1170 Inits.push_back(I->getOperand(i));
1172 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1173 Constant *CV = Context.getNullValue(T1->getElementType());
1174 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1175 Inits.push_back(CV);
1177 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1178 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1179 Inits.push_back(I->getOperand(i));
1181 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1182 Constant *CV = Context.getNullValue(T2->getElementType());
1183 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1184 Inits.push_back(CV);
1186 NG->setInitializer(Context.getConstantArray(NewType, Inits));
1189 // Replace any uses of the two global variables with uses of the new
1192 // FIXME: This should rewrite simple/straight-forward uses such as
1193 // getelementptr instructions to not use the Cast!
1194 G1->replaceAllUsesWith(Context.getConstantExprBitCast(NG,
1196 G2->replaceAllUsesWith(Context.getConstantExprBitCast(NG,
1199 // Remove the two globals from the module now...
1200 M->getGlobalList().erase(G1);
1201 M->getGlobalList().erase(G2);
1203 // Put the new global into the AppendingVars map so that we can handle
1204 // linking of more than two vars...
1205 Second->second = NG;
1207 AppendingVars.erase(First);
1213 static bool ResolveAliases(Module *Dest) {
1214 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1216 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1217 if (GV != I && !GV->isDeclaration())
1218 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
1223 // LinkModules - This function links two modules together, with the resulting
1224 // left module modified to be the composite of the two input modules. If an
1225 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1226 // the problem. Upon failure, the Dest module could be in a modified state, and
1227 // shouldn't be relied on to be consistent.
1229 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1230 assert(Dest != 0 && "Invalid Destination module");
1231 assert(Src != 0 && "Invalid Source Module");
1233 if (Dest->getDataLayout().empty()) {
1234 if (!Src->getDataLayout().empty()) {
1235 Dest->setDataLayout(Src->getDataLayout());
1237 std::string DataLayout;
1239 if (Dest->getEndianness() == Module::AnyEndianness) {
1240 if (Src->getEndianness() == Module::BigEndian)
1241 DataLayout.append("E");
1242 else if (Src->getEndianness() == Module::LittleEndian)
1243 DataLayout.append("e");
1246 if (Dest->getPointerSize() == Module::AnyPointerSize) {
1247 if (Src->getPointerSize() == Module::Pointer64)
1248 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1249 else if (Src->getPointerSize() == Module::Pointer32)
1250 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1252 Dest->setDataLayout(DataLayout);
1256 // Copy the target triple from the source to dest if the dest's is empty.
1257 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1258 Dest->setTargetTriple(Src->getTargetTriple());
1260 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1261 Src->getDataLayout() != Dest->getDataLayout())
1262 cerr << "WARNING: Linking two modules of different data layouts!\n";
1263 if (!Src->getTargetTriple().empty() &&
1264 Dest->getTargetTriple() != Src->getTargetTriple())
1265 cerr << "WARNING: Linking two modules of different target triples!\n";
1267 // Append the module inline asm string.
1268 if (!Src->getModuleInlineAsm().empty()) {
1269 if (Dest->getModuleInlineAsm().empty())
1270 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1272 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1273 Src->getModuleInlineAsm());
1276 // Update the destination module's dependent libraries list with the libraries
1277 // from the source module. There's no opportunity for duplicates here as the
1278 // Module ensures that duplicate insertions are discarded.
1279 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1281 Dest->addLibrary(*SI);
1283 // LinkTypes - Go through the symbol table of the Src module and see if any
1284 // types are named in the src module that are not named in the Dst module.
1285 // Make sure there are no type name conflicts.
1286 if (LinkTypes(Dest, Src, ErrorMsg))
1289 // ValueMap - Mapping of values from what they used to be in Src, to what they
1291 std::map<const Value*, Value*> ValueMap;
1293 // AppendingVars - Keep track of global variables in the destination module
1294 // with appending linkage. After the module is linked together, they are
1295 // appended and the module is rewritten.
1296 std::multimap<std::string, GlobalVariable *> AppendingVars;
1297 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1299 // Add all of the appending globals already in the Dest module to
1301 if (I->hasAppendingLinkage())
1302 AppendingVars.insert(std::make_pair(I->getName(), I));
1305 // Insert all of the globals in src into the Dest module... without linking
1306 // initializers (which could refer to functions not yet mapped over).
1307 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1310 // Link the functions together between the two modules, without doing function
1311 // bodies... this just adds external function prototypes to the Dest
1312 // function... We do this so that when we begin processing function bodies,
1313 // all of the global values that may be referenced are available in our
1315 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1318 // If there were any alias, link them now. We really need to do this now,
1319 // because all of the aliases that may be referenced need to be available in
1321 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1323 // Update the initializers in the Dest module now that all globals that may
1324 // be referenced are in Dest.
1325 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1327 // Link in the function bodies that are defined in the source module into the
1328 // DestModule. This consists basically of copying the function over and
1329 // fixing up references to values.
1330 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1332 // If there were any appending global variables, link them together now.
1333 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1335 // Resolve all uses of aliases with aliasees
1336 if (ResolveAliases(Dest)) return true;
1338 // If the source library's module id is in the dependent library list of the
1339 // destination library, remove it since that module is now linked in.
1341 modId.set(Src->getModuleIdentifier());
1342 if (!modId.isEmpty())
1343 Dest->removeLibrary(modId.getBasename());