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 //===----------------------------------------------------------------------===//
14 #include "llvm/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/TypeFinder.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
31 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
34 //===----------------------------------------------------------------------===//
35 // TypeMap implementation.
36 //===----------------------------------------------------------------------===//
39 typedef SmallPtrSet<StructType*, 32> TypeSet;
41 class TypeMapTy : public ValueMapTypeRemapper {
42 /// MappedTypes - This is a mapping from a source type to a destination type
44 DenseMap<Type*, Type*> MappedTypes;
46 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
47 /// we speculatively add types to MappedTypes, but keep track of them here in
48 /// case we need to roll back.
49 SmallVector<Type*, 16> SpeculativeTypes;
51 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
52 /// source module that are mapped to an opaque struct in the destination
54 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
56 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
57 /// destination modules who are getting a body from the source module.
58 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
61 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
63 TypeSet &DstStructTypesSet;
64 /// addTypeMapping - Indicate that the specified type in the destination
65 /// module is conceptually equivalent to the specified type in the source
67 void addTypeMapping(Type *DstTy, Type *SrcTy);
69 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
70 /// module from a type definition in the source module.
71 void linkDefinedTypeBodies();
73 /// get - Return the mapped type to use for the specified input type from the
75 Type *get(Type *SrcTy);
77 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
79 /// dump - Dump out the type map for debugging purposes.
81 for (DenseMap<Type*, Type*>::const_iterator
82 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
83 dbgs() << "TypeMap: ";
92 Type *getImpl(Type *T);
93 /// remapType - Implement the ValueMapTypeRemapper interface.
94 Type *remapType(Type *SrcTy) {
98 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
102 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
103 Type *&Entry = MappedTypes[SrcTy];
106 if (DstTy == SrcTy) {
111 // Check to see if these types are recursively isomorphic and establish a
112 // mapping between them if so.
113 if (!areTypesIsomorphic(DstTy, SrcTy)) {
114 // Oops, they aren't isomorphic. Just discard this request by rolling out
115 // any speculative mappings we've established.
116 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
117 MappedTypes.erase(SpeculativeTypes[i]);
119 SpeculativeTypes.clear();
122 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
123 /// if they are isomorphic, false if they are not.
124 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
125 // Two types with differing kinds are clearly not isomorphic.
126 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
128 // If we have an entry in the MappedTypes table, then we have our answer.
129 Type *&Entry = MappedTypes[SrcTy];
131 return Entry == DstTy;
133 // Two identical types are clearly isomorphic. Remember this
134 // non-speculatively.
135 if (DstTy == SrcTy) {
140 // Okay, we have two types with identical kinds that we haven't seen before.
142 // If this is an opaque struct type, special case it.
143 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
144 // Mapping an opaque type to any struct, just keep the dest struct.
145 if (SSTy->isOpaque()) {
147 SpeculativeTypes.push_back(SrcTy);
151 // Mapping a non-opaque source type to an opaque dest. If this is the first
152 // type that we're mapping onto this destination type then we succeed. Keep
153 // the dest, but fill it in later. This doesn't need to be speculative. If
154 // this is the second (different) type that we're trying to map onto the
155 // same opaque type then we fail.
156 if (cast<StructType>(DstTy)->isOpaque()) {
157 // We can only map one source type onto the opaque destination type.
158 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
160 SrcDefinitionsToResolve.push_back(SSTy);
166 // If the number of subtypes disagree between the two types, then we fail.
167 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
170 // Fail if any of the extra properties (e.g. array size) of the type disagree.
171 if (isa<IntegerType>(DstTy))
172 return false; // bitwidth disagrees.
173 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
177 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
180 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181 StructType *SSTy = cast<StructType>(SrcTy);
182 if (DSTy->isLiteral() != SSTy->isLiteral() ||
183 DSTy->isPacked() != SSTy->isPacked())
185 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
188 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
189 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
193 // Otherwise, we speculate that these two types will line up and recursively
194 // check the subelements.
196 SpeculativeTypes.push_back(SrcTy);
198 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
199 if (!areTypesIsomorphic(DstTy->getContainedType(i),
200 SrcTy->getContainedType(i)))
203 // If everything seems to have lined up, then everything is great.
207 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
208 /// module from a type definition in the source module.
209 void TypeMapTy::linkDefinedTypeBodies() {
210 SmallVector<Type*, 16> Elements;
211 SmallString<16> TmpName;
213 // Note that processing entries in this loop (calling 'get') can add new
214 // entries to the SrcDefinitionsToResolve vector.
215 while (!SrcDefinitionsToResolve.empty()) {
216 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
217 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
219 // TypeMap is a many-to-one mapping, if there were multiple types that
220 // provide a body for DstSTy then previous iterations of this loop may have
221 // already handled it. Just ignore this case.
222 if (!DstSTy->isOpaque()) continue;
223 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
225 // Map the body of the source type over to a new body for the dest type.
226 Elements.resize(SrcSTy->getNumElements());
227 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
228 Elements[i] = getImpl(SrcSTy->getElementType(i));
230 DstSTy->setBody(Elements, SrcSTy->isPacked());
232 // If DstSTy has no name or has a longer name than STy, then viciously steal
234 if (!SrcSTy->hasName()) continue;
235 StringRef SrcName = SrcSTy->getName();
237 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
238 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
240 DstSTy->setName(TmpName.str());
245 DstResolvedOpaqueTypes.clear();
248 /// get - Return the mapped type to use for the specified input type from the
250 Type *TypeMapTy::get(Type *Ty) {
251 Type *Result = getImpl(Ty);
253 // If this caused a reference to any struct type, resolve it before returning.
254 if (!SrcDefinitionsToResolve.empty())
255 linkDefinedTypeBodies();
259 /// getImpl - This is the recursive version of get().
260 Type *TypeMapTy::getImpl(Type *Ty) {
261 // If we already have an entry for this type, return it.
262 Type **Entry = &MappedTypes[Ty];
263 if (*Entry) return *Entry;
265 // If this is not a named struct type, then just map all of the elements and
266 // then rebuild the type from inside out.
267 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
268 // If there are no element types to map, then the type is itself. This is
269 // true for the anonymous {} struct, things like 'float', integers, etc.
270 if (Ty->getNumContainedTypes() == 0)
273 // Remap all of the elements, keeping track of whether any of them change.
274 bool AnyChange = false;
275 SmallVector<Type*, 4> ElementTypes;
276 ElementTypes.resize(Ty->getNumContainedTypes());
277 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
278 ElementTypes[i] = getImpl(Ty->getContainedType(i));
279 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
282 // If we found our type while recursively processing stuff, just use it.
283 Entry = &MappedTypes[Ty];
284 if (*Entry) return *Entry;
286 // If all of the element types mapped directly over, then the type is usable
291 // Otherwise, rebuild a modified type.
292 switch (Ty->getTypeID()) {
293 default: llvm_unreachable("unknown derived type to remap");
294 case Type::ArrayTyID:
295 return *Entry = ArrayType::get(ElementTypes[0],
296 cast<ArrayType>(Ty)->getNumElements());
297 case Type::VectorTyID:
298 return *Entry = VectorType::get(ElementTypes[0],
299 cast<VectorType>(Ty)->getNumElements());
300 case Type::PointerTyID:
301 return *Entry = PointerType::get(ElementTypes[0],
302 cast<PointerType>(Ty)->getAddressSpace());
303 case Type::FunctionTyID:
304 return *Entry = FunctionType::get(ElementTypes[0],
305 makeArrayRef(ElementTypes).slice(1),
306 cast<FunctionType>(Ty)->isVarArg());
307 case Type::StructTyID:
308 // Note that this is only reached for anonymous structs.
309 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
310 cast<StructType>(Ty)->isPacked());
314 // Otherwise, this is an unmapped named struct. If the struct can be directly
315 // mapped over, just use it as-is. This happens in a case when the linked-in
316 // module has something like:
317 // %T = type {%T*, i32}
318 // @GV = global %T* null
319 // where T does not exist at all in the destination module.
321 // The other case we watch for is when the type is not in the destination
322 // module, but that it has to be rebuilt because it refers to something that
323 // is already mapped. For example, if the destination module has:
325 // and the source module has something like
326 // %A' = type { i32 }
327 // %B = type { %A'* }
328 // @GV = global %B* null
329 // then we want to create a new type: "%B = type { %A*}" and have it take the
330 // pristine "%B" name from the source module.
332 // To determine which case this is, we have to recursively walk the type graph
333 // speculating that we'll be able to reuse it unmodified. Only if this is
334 // safe would we map the entire thing over. Because this is an optimization,
335 // and is not required for the prettiness of the linked module, we just skip
336 // it and always rebuild a type here.
337 StructType *STy = cast<StructType>(Ty);
339 // If the type is opaque, we can just use it directly.
340 if (STy->isOpaque()) {
341 // A named structure type from src module is used. Add it to the Set of
342 // identified structs in the destination module.
343 DstStructTypesSet.insert(STy);
347 // Otherwise we create a new type and resolve its body later. This will be
348 // resolved by the top level of get().
349 SrcDefinitionsToResolve.push_back(STy);
350 StructType *DTy = StructType::create(STy->getContext());
351 // A new identified structure type was created. Add it to the set of
352 // identified structs in the destination module.
353 DstStructTypesSet.insert(DTy);
354 DstResolvedOpaqueTypes.insert(DTy);
358 //===----------------------------------------------------------------------===//
359 // ModuleLinker implementation.
360 //===----------------------------------------------------------------------===//
365 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
366 /// linked on the fly. This speeds up linking for modules with many
367 /// lazily linked functions of which few get used.
368 class ValueMaterializerTy : public ValueMaterializer {
371 std::vector<Function*> &LazilyLinkFunctions;
373 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
374 std::vector<Function*> &LazilyLinkFunctions) :
375 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
376 LazilyLinkFunctions(LazilyLinkFunctions) {
379 virtual Value *materializeValueFor(Value *V);
382 /// ModuleLinker - This is an implementation class for the LinkModules
383 /// function, which is the entrypoint for this file.
388 ValueMaterializerTy ValMaterializer;
390 /// ValueMap - Mapping of values from what they used to be in Src, to what
391 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
392 /// some overhead due to the use of Value handles which the Linker doesn't
393 /// actually need, but this allows us to reuse the ValueMapper code.
394 ValueToValueMapTy ValueMap;
396 struct AppendingVarInfo {
397 GlobalVariable *NewGV; // New aggregate global in dest module.
398 Constant *DstInit; // Old initializer from dest module.
399 Constant *SrcInit; // Old initializer from src module.
402 std::vector<AppendingVarInfo> AppendingVars;
404 unsigned Mode; // Mode to treat source module.
406 // Set of items not to link in from source.
407 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
409 // Vector of functions to lazily link in.
410 std::vector<Function*> LazilyLinkFunctions;
413 std::string ErrorMsg;
415 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
416 : DstM(dstM), SrcM(srcM), TypeMap(Set),
417 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
423 /// emitError - Helper method for setting a message and returning an error
425 bool emitError(const Twine &Message) {
426 ErrorMsg = Message.str();
430 /// getLinkageResult - This analyzes the two global values and determines
431 /// what the result will look like in the destination module.
432 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
433 GlobalValue::LinkageTypes <,
434 GlobalValue::VisibilityTypes &Vis,
437 /// getLinkedToGlobal - Given a global in the source module, return the
438 /// global in the destination module that is being linked to, if any.
439 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
440 // If the source has no name it can't link. If it has local linkage,
441 // there is no name match-up going on.
442 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
445 // Otherwise see if we have a match in the destination module's symtab.
446 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
447 if (DGV == 0) return 0;
449 // If we found a global with the same name in the dest module, but it has
450 // internal linkage, we are really not doing any linkage here.
451 if (DGV->hasLocalLinkage())
454 // Otherwise, we do in fact link to the destination global.
458 void computeTypeMapping();
460 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
461 bool linkGlobalProto(GlobalVariable *SrcGV);
462 bool linkFunctionProto(Function *SrcF);
463 bool linkAliasProto(GlobalAlias *SrcA);
464 bool linkModuleFlagsMetadata();
466 void linkAppendingVarInit(const AppendingVarInfo &AVI);
467 void linkGlobalInits();
468 void linkFunctionBody(Function *Dst, Function *Src);
469 void linkAliasBodies();
470 void linkNamedMDNodes();
474 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
475 /// in the symbol table. This is good for all clients except for us. Go
476 /// through the trouble to force this back.
477 static void forceRenaming(GlobalValue *GV, StringRef Name) {
478 // If the global doesn't force its name or if it already has the right name,
479 // there is nothing for us to do.
480 if (GV->hasLocalLinkage() || GV->getName() == Name)
483 Module *M = GV->getParent();
485 // If there is a conflict, rename the conflict.
486 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
487 GV->takeName(ConflictGV);
488 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
489 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
491 GV->setName(Name); // Force the name back
495 /// copyGVAttributes - copy additional attributes (those not needed to construct
496 /// a GlobalValue) from the SrcGV to the DestGV.
497 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
498 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
499 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
500 DestGV->copyAttributesFrom(SrcGV);
501 DestGV->setAlignment(Alignment);
503 forceRenaming(DestGV, SrcGV->getName());
506 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
507 GlobalValue::VisibilityTypes b) {
508 if (a == GlobalValue::HiddenVisibility)
510 if (b == GlobalValue::HiddenVisibility)
512 if (a == GlobalValue::ProtectedVisibility)
514 if (b == GlobalValue::ProtectedVisibility)
519 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
520 Function *SF = dyn_cast<Function>(V);
524 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
525 SF->getLinkage(), SF->getName(), DstM);
526 copyGVAttributes(DF, SF);
528 LazilyLinkFunctions.push_back(SF);
533 /// getLinkageResult - This analyzes the two global values and determines what
534 /// the result will look like in the destination module. In particular, it
535 /// computes the resultant linkage type and visibility, computes whether the
536 /// global in the source should be copied over to the destination (replacing
537 /// the existing one), and computes whether this linkage is an error or not.
538 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
539 GlobalValue::LinkageTypes <,
540 GlobalValue::VisibilityTypes &Vis,
542 assert(Dest && "Must have two globals being queried");
543 assert(!Src->hasLocalLinkage() &&
544 "If Src has internal linkage, Dest shouldn't be set!");
546 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
547 bool DestIsDeclaration = Dest->isDeclaration();
549 if (SrcIsDeclaration) {
550 // If Src is external or if both Src & Dest are external.. Just link the
551 // external globals, we aren't adding anything.
552 if (Src->hasDLLImportStorageClass()) {
553 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
554 if (DestIsDeclaration) {
556 LT = Src->getLinkage();
558 } else if (Dest->hasExternalWeakLinkage()) {
559 // If the Dest is weak, use the source linkage.
561 LT = Src->getLinkage();
564 LT = Dest->getLinkage();
566 } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
567 // If Dest is external but Src is not:
569 LT = Src->getLinkage();
570 } else if (Src->isWeakForLinker()) {
571 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
573 if (Dest->hasExternalWeakLinkage() ||
574 Dest->hasAvailableExternallyLinkage() ||
575 (Dest->hasLinkOnceLinkage() &&
576 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
578 LT = Src->getLinkage();
581 LT = Dest->getLinkage();
583 } else if (Dest->isWeakForLinker()) {
584 // At this point we know that Src has External* or DLL* linkage.
585 if (Src->hasExternalWeakLinkage()) {
587 LT = Dest->getLinkage();
590 LT = GlobalValue::ExternalLinkage;
593 assert((Dest->hasExternalLinkage() || Dest->hasExternalWeakLinkage()) &&
594 (Src->hasExternalLinkage() || Src->hasExternalWeakLinkage()) &&
595 "Unexpected linkage type!");
596 return emitError("Linking globals named '" + Src->getName() +
597 "': symbol multiply defined!");
600 // Compute the visibility. We follow the rules in the System V Application
602 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
603 Dest->getVisibility() : Src->getVisibility();
607 /// computeTypeMapping - Loop over all of the linked values to compute type
608 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
609 /// we have two struct types 'Foo' but one got renamed when the module was
610 /// loaded into the same LLVMContext.
611 void ModuleLinker::computeTypeMapping() {
612 // Incorporate globals.
613 for (Module::global_iterator I = SrcM->global_begin(),
614 E = SrcM->global_end(); I != E; ++I) {
615 GlobalValue *DGV = getLinkedToGlobal(I);
616 if (DGV == 0) continue;
618 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
619 TypeMap.addTypeMapping(DGV->getType(), I->getType());
623 // Unify the element type of appending arrays.
624 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
625 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
626 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
629 // Incorporate functions.
630 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
631 if (GlobalValue *DGV = getLinkedToGlobal(I))
632 TypeMap.addTypeMapping(DGV->getType(), I->getType());
635 // Incorporate types by name, scanning all the types in the source module.
636 // At this point, the destination module may have a type "%foo = { i32 }" for
637 // example. When the source module got loaded into the same LLVMContext, if
638 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
639 TypeFinder SrcStructTypes;
640 SrcStructTypes.run(*SrcM, true);
641 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
642 SrcStructTypes.end());
644 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
645 StructType *ST = SrcStructTypes[i];
646 if (!ST->hasName()) continue;
648 // Check to see if there is a dot in the name followed by a digit.
649 size_t DotPos = ST->getName().rfind('.');
650 if (DotPos == 0 || DotPos == StringRef::npos ||
651 ST->getName().back() == '.' ||
652 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
655 // Check to see if the destination module has a struct with the prefix name.
656 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
657 // Don't use it if this actually came from the source module. They're in
658 // the same LLVMContext after all. Also don't use it unless the type is
659 // actually used in the destination module. This can happen in situations
664 // %Z = type { %A } %B = type { %C.1 }
665 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
666 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
667 // %C = type { i8* } %B.3 = type { %C.1 }
669 // When we link Module B with Module A, the '%B' in Module B is
670 // used. However, that would then use '%C.1'. But when we process '%C.1',
671 // we prefer to take the '%C' version. So we are then left with both
672 // '%C.1' and '%C' being used for the same types. This leads to some
673 // variables using one type and some using the other.
674 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
675 TypeMap.addTypeMapping(DST, ST);
678 // Don't bother incorporating aliases, they aren't generally typed well.
680 // Now that we have discovered all of the type equivalences, get a body for
681 // any 'opaque' types in the dest module that are now resolved.
682 TypeMap.linkDefinedTypeBodies();
685 /// linkAppendingVarProto - If there were any appending global variables, link
686 /// them together now. Return true on error.
687 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
688 GlobalVariable *SrcGV) {
690 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
691 return emitError("Linking globals named '" + SrcGV->getName() +
692 "': can only link appending global with another appending global!");
694 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
696 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
697 Type *EltTy = DstTy->getElementType();
699 // Check to see that they two arrays agree on type.
700 if (EltTy != SrcTy->getElementType())
701 return emitError("Appending variables with different element types!");
702 if (DstGV->isConstant() != SrcGV->isConstant())
703 return emitError("Appending variables linked with different const'ness!");
705 if (DstGV->getAlignment() != SrcGV->getAlignment())
707 "Appending variables with different alignment need to be linked!");
709 if (DstGV->getVisibility() != SrcGV->getVisibility())
711 "Appending variables with different visibility need to be linked!");
713 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
715 "Appending variables with different unnamed_addr need to be linked!");
717 if (DstGV->getSection() != SrcGV->getSection())
719 "Appending variables with different section name need to be linked!");
721 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
722 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
724 // Create the new global variable.
726 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
727 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
728 DstGV->getThreadLocalMode(),
729 DstGV->getType()->getAddressSpace());
731 // Propagate alignment, visibility and section info.
732 copyGVAttributes(NG, DstGV);
734 AppendingVarInfo AVI;
736 AVI.DstInit = DstGV->getInitializer();
737 AVI.SrcInit = SrcGV->getInitializer();
738 AppendingVars.push_back(AVI);
740 // Replace any uses of the two global variables with uses of the new
742 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
744 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
745 DstGV->eraseFromParent();
747 // Track the source variable so we don't try to link it.
748 DoNotLinkFromSource.insert(SrcGV);
753 /// linkGlobalProto - Loop through the global variables in the src module and
754 /// merge them into the dest module.
755 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
756 GlobalValue *DGV = getLinkedToGlobal(SGV);
757 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
758 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
761 // Concatenation of appending linkage variables is magic and handled later.
762 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
763 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
765 // Determine whether linkage of these two globals follows the source
766 // module's definition or the destination module's definition.
767 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
768 GlobalValue::VisibilityTypes NV;
769 bool LinkFromSrc = false;
770 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
773 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
775 // If we're not linking from the source, then keep the definition that we
778 // Special case for const propagation.
779 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
780 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
781 DGVar->setConstant(true);
783 // Set calculated linkage, visibility and unnamed_addr.
784 DGV->setLinkage(NewLinkage);
785 DGV->setVisibility(*NewVisibility);
786 DGV->setUnnamedAddr(HasUnnamedAddr);
788 // Make sure to remember this mapping.
789 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
791 // Track the source global so that we don't attempt to copy it over when
792 // processing global initializers.
793 DoNotLinkFromSource.insert(SGV);
799 // No linking to be performed or linking from the source: simply create an
800 // identical version of the symbol over in the dest module... the
801 // initializer will be filled in later by LinkGlobalInits.
802 GlobalVariable *NewDGV =
803 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
804 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
805 SGV->getName(), /*insertbefore*/0,
806 SGV->getThreadLocalMode(),
807 SGV->getType()->getAddressSpace());
808 // Propagate alignment, visibility and section info.
809 copyGVAttributes(NewDGV, SGV);
811 NewDGV->setVisibility(*NewVisibility);
812 NewDGV->setUnnamedAddr(HasUnnamedAddr);
815 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
816 DGV->eraseFromParent();
819 // Make sure to remember this mapping.
820 ValueMap[SGV] = NewDGV;
824 /// linkFunctionProto - Link the function in the source module into the
825 /// destination module if needed, setting up mapping information.
826 bool ModuleLinker::linkFunctionProto(Function *SF) {
827 GlobalValue *DGV = getLinkedToGlobal(SF);
828 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
829 bool HasUnnamedAddr = SF->hasUnnamedAddr();
832 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
833 bool LinkFromSrc = false;
834 GlobalValue::VisibilityTypes NV;
835 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
838 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
841 // Set calculated linkage
842 DGV->setLinkage(NewLinkage);
843 DGV->setVisibility(*NewVisibility);
844 DGV->setUnnamedAddr(HasUnnamedAddr);
846 // Make sure to remember this mapping.
847 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
849 // Track the function from the source module so we don't attempt to remap
851 DoNotLinkFromSource.insert(SF);
857 // If the function is to be lazily linked, don't create it just yet.
858 // The ValueMaterializerTy will deal with creating it if it's used.
859 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
860 SF->hasAvailableExternallyLinkage())) {
861 DoNotLinkFromSource.insert(SF);
865 // If there is no linkage to be performed or we are linking from the source,
867 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
868 SF->getLinkage(), SF->getName(), DstM);
869 copyGVAttributes(NewDF, SF);
871 NewDF->setVisibility(*NewVisibility);
872 NewDF->setUnnamedAddr(HasUnnamedAddr);
875 // Any uses of DF need to change to NewDF, with cast.
876 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
877 DGV->eraseFromParent();
880 ValueMap[SF] = NewDF;
884 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
886 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
887 GlobalValue *DGV = getLinkedToGlobal(SGA);
888 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
891 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
892 GlobalValue::VisibilityTypes NV;
893 bool LinkFromSrc = false;
894 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
899 // Set calculated linkage.
900 DGV->setLinkage(NewLinkage);
901 DGV->setVisibility(*NewVisibility);
903 // Make sure to remember this mapping.
904 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
906 // Track the alias from the source module so we don't attempt to remap it.
907 DoNotLinkFromSource.insert(SGA);
913 // If there is no linkage to be performed or we're linking from the source,
915 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
916 SGA->getLinkage(), SGA->getName(),
918 copyGVAttributes(NewDA, SGA);
920 NewDA->setVisibility(*NewVisibility);
923 // Any uses of DGV need to change to NewDA, with cast.
924 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
925 DGV->eraseFromParent();
928 ValueMap[SGA] = NewDA;
932 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
933 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
935 for (unsigned i = 0; i != NumElements; ++i)
936 Dest.push_back(C->getAggregateElement(i));
939 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
940 // Merge the initializer.
941 SmallVector<Constant*, 16> Elements;
942 getArrayElements(AVI.DstInit, Elements);
944 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
945 getArrayElements(SrcInit, Elements);
947 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
948 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
951 /// linkGlobalInits - Update the initializers in the Dest module now that all
952 /// globals that may be referenced are in Dest.
953 void ModuleLinker::linkGlobalInits() {
954 // Loop over all of the globals in the src module, mapping them over as we go
955 for (Module::const_global_iterator I = SrcM->global_begin(),
956 E = SrcM->global_end(); I != E; ++I) {
958 // Only process initialized GV's or ones not already in dest.
959 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
961 // Grab destination global variable.
962 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
963 // Figure out what the initializer looks like in the dest module.
964 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
965 RF_None, &TypeMap, &ValMaterializer));
969 /// linkFunctionBody - Copy the source function over into the dest function and
970 /// fix up references to values. At this point we know that Dest is an external
971 /// function, and that Src is not.
972 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
973 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
975 // Go through and convert function arguments over, remembering the mapping.
976 Function::arg_iterator DI = Dst->arg_begin();
977 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
979 DI->setName(I->getName()); // Copy the name over.
981 // Add a mapping to our mapping.
985 if (Mode == Linker::DestroySource) {
986 // Splice the body of the source function into the dest function.
987 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
989 // At this point, all of the instructions and values of the function are now
990 // copied over. The only problem is that they are still referencing values in
991 // the Source function as operands. Loop through all of the operands of the
992 // functions and patch them up to point to the local versions.
993 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
994 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
995 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
996 &TypeMap, &ValMaterializer);
999 // Clone the body of the function into the dest function.
1000 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1001 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL,
1002 &TypeMap, &ValMaterializer);
1005 // There is no need to map the arguments anymore.
1006 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1012 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1013 void ModuleLinker::linkAliasBodies() {
1014 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1016 if (DoNotLinkFromSource.count(I))
1018 if (Constant *Aliasee = I->getAliasee()) {
1019 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1020 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None,
1021 &TypeMap, &ValMaterializer));
1026 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1028 void ModuleLinker::linkNamedMDNodes() {
1029 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1030 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1031 E = SrcM->named_metadata_end(); I != E; ++I) {
1032 // Don't link module flags here. Do them separately.
1033 if (&*I == SrcModFlags) continue;
1034 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1035 // Add Src elements into Dest node.
1036 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1037 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1038 RF_None, &TypeMap, &ValMaterializer));
1042 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1044 bool ModuleLinker::linkModuleFlagsMetadata() {
1045 // If the source module has no module flags, we are done.
1046 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1047 if (!SrcModFlags) return false;
1049 // If the destination module doesn't have module flags yet, then just copy
1050 // over the source module's flags.
1051 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1052 if (DstModFlags->getNumOperands() == 0) {
1053 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1054 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1059 // First build a map of the existing module flags and requirements.
1060 DenseMap<MDString*, MDNode*> Flags;
1061 SmallSetVector<MDNode*, 16> Requirements;
1062 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1063 MDNode *Op = DstModFlags->getOperand(I);
1064 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1065 MDString *ID = cast<MDString>(Op->getOperand(1));
1067 if (Behavior->getZExtValue() == Module::Require) {
1068 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1074 // Merge in the flags from the source module, and also collect its set of
1076 bool HasErr = false;
1077 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1078 MDNode *SrcOp = SrcModFlags->getOperand(I);
1079 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1080 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1081 MDNode *DstOp = Flags.lookup(ID);
1082 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1084 // If this is a requirement, add it and continue.
1085 if (SrcBehaviorValue == Module::Require) {
1086 // If the destination module does not already have this requirement, add
1088 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1089 DstModFlags->addOperand(SrcOp);
1094 // If there is no existing flag with this ID, just add it.
1097 DstModFlags->addOperand(SrcOp);
1101 // Otherwise, perform a merge.
1102 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1103 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1105 // If either flag has override behavior, handle it first.
1106 if (DstBehaviorValue == Module::Override) {
1107 // Diagnose inconsistent flags which both have override behavior.
1108 if (SrcBehaviorValue == Module::Override &&
1109 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1110 HasErr |= emitError("linking module flags '" + ID->getString() +
1111 "': IDs have conflicting override values");
1114 } else if (SrcBehaviorValue == Module::Override) {
1115 // Update the destination flag to that of the source.
1116 DstOp->replaceOperandWith(0, SrcBehavior);
1117 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1121 // Diagnose inconsistent merge behavior types.
1122 if (SrcBehaviorValue != DstBehaviorValue) {
1123 HasErr |= emitError("linking module flags '" + ID->getString() +
1124 "': IDs have conflicting behaviors");
1128 // Perform the merge for standard behavior types.
1129 switch (SrcBehaviorValue) {
1130 case Module::Require:
1131 case Module::Override: assert(0 && "not possible"); break;
1132 case Module::Error: {
1133 // Emit an error if the values differ.
1134 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1135 HasErr |= emitError("linking module flags '" + ID->getString() +
1136 "': IDs have conflicting values");
1140 case Module::Warning: {
1141 // Emit a warning if the values differ.
1142 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1143 if (!SuppressWarnings) {
1144 errs() << "WARNING: linking module flags '" << ID->getString()
1145 << "': IDs have conflicting values";
1150 case Module::Append: {
1151 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1152 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1153 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1154 Value **VP, **Values = VP = new Value*[NumOps];
1155 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1156 *VP = DstValue->getOperand(i);
1157 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1158 *VP = SrcValue->getOperand(i);
1159 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1160 ArrayRef<Value*>(Values,
1165 case Module::AppendUnique: {
1166 SmallSetVector<Value*, 16> Elts;
1167 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1168 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1169 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1170 Elts.insert(DstValue->getOperand(i));
1171 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1172 Elts.insert(SrcValue->getOperand(i));
1173 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1174 ArrayRef<Value*>(Elts.begin(),
1181 // Check all of the requirements.
1182 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1183 MDNode *Requirement = Requirements[I];
1184 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1185 Value *ReqValue = Requirement->getOperand(1);
1187 MDNode *Op = Flags[Flag];
1188 if (!Op || Op->getOperand(2) != ReqValue) {
1189 HasErr |= emitError("linking module flags '" + Flag->getString() +
1190 "': does not have the required value");
1198 bool ModuleLinker::run() {
1199 assert(DstM && "Null destination module");
1200 assert(SrcM && "Null source module");
1202 // Inherit the target data from the source module if the destination module
1203 // doesn't have one already.
1204 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1205 DstM->setDataLayout(SrcM->getDataLayout());
1207 // Copy the target triple from the source to dest if the dest's is empty.
1208 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1209 DstM->setTargetTriple(SrcM->getTargetTriple());
1211 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1212 SrcM->getDataLayout() != DstM->getDataLayout()) {
1213 if (!SuppressWarnings) {
1214 errs() << "WARNING: Linking two modules of different data layouts!\n";
1217 if (!SrcM->getTargetTriple().empty() &&
1218 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1219 if (!SuppressWarnings) {
1220 errs() << "WARNING: Linking two modules of different target triples: ";
1221 if (!SrcM->getModuleIdentifier().empty())
1222 errs() << SrcM->getModuleIdentifier() << ": ";
1223 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1224 << DstM->getTargetTriple() << "'\n";
1228 // Append the module inline asm string.
1229 if (!SrcM->getModuleInlineAsm().empty()) {
1230 if (DstM->getModuleInlineAsm().empty())
1231 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1233 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1234 SrcM->getModuleInlineAsm());
1237 // Loop over all of the linked values to compute type mappings.
1238 computeTypeMapping();
1240 // Insert all of the globals in src into the DstM module... without linking
1241 // initializers (which could refer to functions not yet mapped over).
1242 for (Module::global_iterator I = SrcM->global_begin(),
1243 E = SrcM->global_end(); I != E; ++I)
1244 if (linkGlobalProto(I))
1247 // Link the functions together between the two modules, without doing function
1248 // bodies... this just adds external function prototypes to the DstM
1249 // function... We do this so that when we begin processing function bodies,
1250 // all of the global values that may be referenced are available in our
1252 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1253 if (linkFunctionProto(I))
1256 // If there were any aliases, link them now.
1257 for (Module::alias_iterator I = SrcM->alias_begin(),
1258 E = SrcM->alias_end(); I != E; ++I)
1259 if (linkAliasProto(I))
1262 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1263 linkAppendingVarInit(AppendingVars[i]);
1265 // Link in the function bodies that are defined in the source module into
1267 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1268 // Skip if not linking from source.
1269 if (DoNotLinkFromSource.count(SF)) continue;
1271 Function *DF = cast<Function>(ValueMap[SF]);
1272 if (SF->hasPrefixData()) {
1273 // Link in the prefix data.
1274 DF->setPrefixData(MapValue(
1275 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1278 // Skip if no body (function is external) or materialize.
1279 if (SF->isDeclaration()) {
1280 if (!SF->isMaterializable())
1282 if (SF->Materialize(&ErrorMsg))
1286 linkFunctionBody(DF, SF);
1287 SF->Dematerialize();
1290 // Resolve all uses of aliases with aliasees.
1293 // Remap all of the named MDNodes in Src into the DstM module. We do this
1294 // after linking GlobalValues so that MDNodes that reference GlobalValues
1295 // are properly remapped.
1298 // Merge the module flags into the DstM module.
1299 if (linkModuleFlagsMetadata())
1302 // Update the initializers in the DstM module now that all globals that may
1303 // be referenced are in DstM.
1306 // Process vector of lazily linked in functions.
1307 bool LinkedInAnyFunctions;
1309 LinkedInAnyFunctions = false;
1311 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1312 E = LazilyLinkFunctions.end(); I != E; ++I) {
1317 Function *DF = cast<Function>(ValueMap[SF]);
1318 if (SF->hasPrefixData()) {
1319 // Link in the prefix data.
1320 DF->setPrefixData(MapValue(SF->getPrefixData(),
1327 // Materialize if necessary.
1328 if (SF->isDeclaration()) {
1329 if (!SF->isMaterializable())
1331 if (SF->Materialize(&ErrorMsg))
1335 // Erase from vector *before* the function body is linked - linkFunctionBody could
1337 LazilyLinkFunctions.erase(I);
1339 // Link in function body.
1340 linkFunctionBody(DF, SF);
1341 SF->Dematerialize();
1343 // Set flag to indicate we may have more functions to lazily link in
1344 // since we linked in a function.
1345 LinkedInAnyFunctions = true;
1348 } while (LinkedInAnyFunctions);
1350 // Now that all of the types from the source are used, resolve any structs
1351 // copied over to the dest that didn't exist there.
1352 TypeMap.linkDefinedTypeBodies();
1357 Linker::Linker(Module *M) : Composite(M) {
1358 TypeFinder StructTypes;
1359 StructTypes.run(*M, true);
1360 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1366 void Linker::deleteModule() {
1371 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1372 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
1373 if (TheLinker.run()) {
1375 *ErrorMsg = TheLinker.ErrorMsg;
1381 //===----------------------------------------------------------------------===//
1382 // LinkModules entrypoint.
1383 //===----------------------------------------------------------------------===//
1385 /// LinkModules - This function links two modules together, with the resulting
1386 /// Dest module modified to be the composite of the two input modules. If an
1387 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1388 /// the problem. Upon failure, the Dest module could be in a modified state,
1389 /// and shouldn't be relied on to be consistent.
1390 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1391 std::string *ErrorMsg) {
1393 return L.linkInModule(Src, Mode, ErrorMsg);
1396 //===----------------------------------------------------------------------===//
1398 //===----------------------------------------------------------------------===//
1400 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1401 LLVMLinkerMode Mode, char **OutMessages) {
1402 std::string Messages;
1403 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1404 Mode, OutMessages? &Messages : 0);
1406 *OutMessages = strdup(Messages.c_str());