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/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Transforms/Utils/ValueMapper.h"
23 //===----------------------------------------------------------------------===//
24 // TypeMap implementation.
25 //===----------------------------------------------------------------------===//
28 class TypeMapTy : public ValueMapTypeRemapper {
29 /// MappedTypes - This is a mapping from a source type to a destination type
31 DenseMap<Type*, Type*> MappedTypes;
33 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
34 /// we speculatively add types to MappedTypes, but keep track of them here in
35 /// case we need to roll back.
36 SmallVector<Type*, 16> SpeculativeTypes;
38 /// DefinitionsToResolve - This is a list of non-opaque structs in the source
39 /// module that are mapped to an opaque struct in the destination module.
40 SmallVector<StructType*, 16> DefinitionsToResolve;
43 /// addTypeMapping - Indicate that the specified type in the destination
44 /// module is conceptually equivalent to the specified type in the source
46 void addTypeMapping(Type *DstTy, Type *SrcTy);
48 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
49 /// module from a type definition in the source module.
50 void linkDefinedTypeBodies();
52 /// get - Return the mapped type to use for the specified input type from the
54 Type *get(Type *SrcTy);
56 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
59 Type *getImpl(Type *T);
60 /// remapType - Implement the ValueMapTypeRemapper interface.
61 Type *remapType(Type *SrcTy) {
65 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
69 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
70 Type *&Entry = MappedTypes[SrcTy];
78 // Check to see if these types are recursively isomorphic and establish a
79 // mapping between them if so.
80 if (!areTypesIsomorphic(DstTy, SrcTy)) {
81 // Oops, they aren't isomorphic. Just discard this request by rolling out
82 // any speculative mappings we've established.
83 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
84 MappedTypes.erase(SpeculativeTypes[i]);
86 SpeculativeTypes.clear();
89 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
90 /// if they are isomorphic, false if they are not.
91 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
92 // Two types with differing kinds are clearly not isomorphic.
93 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
95 // If we have an entry in the MappedTypes table, then we have our answer.
96 Type *&Entry = MappedTypes[SrcTy];
98 return Entry == DstTy;
100 // Two identical types are clearly isomorphic. Remember this
101 // non-speculatively.
102 if (DstTy == SrcTy) {
107 // Okay, we have two types with identical kinds that we haven't seen before.
109 // If this is an opaque struct type, special case it.
110 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
111 // Mapping an opaque type to any struct, just keep the dest struct.
112 if (SSTy->isOpaque()) {
114 SpeculativeTypes.push_back(SrcTy);
118 // Mapping a non-opaque source type to an opaque dest. Keep the dest, but
119 // fill it in later. This doesn't need to be speculative.
120 if (cast<StructType>(DstTy)->isOpaque()) {
122 DefinitionsToResolve.push_back(SSTy);
127 // If the number of subtypes disagree between the two types, then we fail.
128 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
131 // Fail if any of the extra properties (e.g. array size) of the type disagree.
132 if (isa<IntegerType>(DstTy))
133 return false; // bitwidth disagrees.
134 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
135 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
137 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
138 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
140 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
141 StructType *SSTy = cast<StructType>(SrcTy);
142 if (DSTy->isLiteral() != SSTy->isLiteral() ||
143 DSTy->isPacked() != SSTy->isPacked())
145 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
146 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
148 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
149 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
153 // Otherwise, we speculate that these two types will line up and recursively
154 // check the subelements.
156 SpeculativeTypes.push_back(SrcTy);
158 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
159 if (!areTypesIsomorphic(DstTy->getContainedType(i),
160 SrcTy->getContainedType(i)))
163 // If everything seems to have lined up, then everything is great.
167 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
168 /// module from a type definition in the source module.
169 void TypeMapTy::linkDefinedTypeBodies() {
170 SmallVector<Type*, 16> Elements;
171 SmallString<16> TmpName;
173 // Note that processing entries in this loop (calling 'get') can add new
174 // entries to the DefinitionsToResolve vector.
175 while (!DefinitionsToResolve.empty()) {
176 StructType *SrcSTy = DefinitionsToResolve.pop_back_val();
177 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
179 // TypeMap is a many-to-one mapping, if there were multiple types that
180 // provide a body for DstSTy then previous iterations of this loop may have
181 // already handled it. Just ignore this case.
182 if (!DstSTy->isOpaque()) continue;
183 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
185 // Map the body of the source type over to a new body for the dest type.
186 Elements.resize(SrcSTy->getNumElements());
187 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
188 Elements[i] = getImpl(SrcSTy->getElementType(i));
190 DstSTy->setBody(Elements, SrcSTy->isPacked());
192 // If DstSTy has no name or has a longer name than STy, then viciously steal
194 if (!SrcSTy->hasName()) continue;
195 StringRef SrcName = SrcSTy->getName();
197 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
198 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
200 DstSTy->setName(TmpName.str());
207 /// get - Return the mapped type to use for the specified input type from the
209 Type *TypeMapTy::get(Type *Ty) {
210 Type *Result = getImpl(Ty);
212 // If this caused a reference to any struct type, resolve it before returning.
213 if (!DefinitionsToResolve.empty())
214 linkDefinedTypeBodies();
218 /// getImpl - This is the recursive version of get().
219 Type *TypeMapTy::getImpl(Type *Ty) {
220 // If we already have an entry for this type, return it.
221 Type **Entry = &MappedTypes[Ty];
222 if (*Entry) return *Entry;
224 // If this is not a named struct type, then just map all of the elements and
225 // then rebuild the type from inside out.
226 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
227 // If there are no element types to map, then the type is itself. This is
228 // true for the anonymous {} struct, things like 'float', integers, etc.
229 if (Ty->getNumContainedTypes() == 0)
232 // Remap all of the elements, keeping track of whether any of them change.
233 bool AnyChange = false;
234 SmallVector<Type*, 4> ElementTypes;
235 ElementTypes.resize(Ty->getNumContainedTypes());
236 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
237 ElementTypes[i] = getImpl(Ty->getContainedType(i));
238 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
241 // If we found our type while recursively processing stuff, just use it.
242 Entry = &MappedTypes[Ty];
243 if (*Entry) return *Entry;
245 // If all of the element types mapped directly over, then the type is usable
250 // Otherwise, rebuild a modified type.
251 switch (Ty->getTypeID()) {
252 default: assert(0 && "unknown derived type to remap");
253 case Type::ArrayTyID:
254 return *Entry = ArrayType::get(ElementTypes[0],
255 cast<ArrayType>(Ty)->getNumElements());
256 case Type::VectorTyID:
257 return *Entry = VectorType::get(ElementTypes[0],
258 cast<VectorType>(Ty)->getNumElements());
259 case Type::PointerTyID:
260 return *Entry = PointerType::get(ElementTypes[0],
261 cast<PointerType>(Ty)->getAddressSpace());
262 case Type::FunctionTyID:
263 return *Entry = FunctionType::get(ElementTypes[0],
264 makeArrayRef(ElementTypes).slice(1),
265 cast<FunctionType>(Ty)->isVarArg());
266 case Type::StructTyID:
267 // Note that this is only reached for anonymous structs.
268 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
269 cast<StructType>(Ty)->isPacked());
273 // Otherwise, this is an unmapped named struct. If the struct can be directly
274 // mapped over, just use it as-is. This happens in a case when the linked-in
275 // module has something like:
276 // %T = type {%T*, i32}
277 // @GV = global %T* null
278 // where T does not exist at all in the destination module.
280 // The other case we watch for is when the type is not in the destination
281 // module, but that it has to be rebuilt because it refers to something that
282 // is already mapped. For example, if the destination module has:
284 // and the source module has something like
285 // %A' = type { i32 }
286 // %B = type { %A'* }
287 // @GV = global %B* null
288 // then we want to create a new type: "%B = type { %A*}" and have it take the
289 // pristine "%B" name from the source module.
291 // To determine which case this is, we have to recursively walk the type graph
292 // speculating that we'll be able to reuse it unmodified. Only if this is
293 // safe would we map the entire thing over. Because this is an optimization,
294 // and is not required for the prettiness of the linked module, we just skip
295 // it and always rebuild a type here.
296 StructType *STy = cast<StructType>(Ty);
298 // If the type is opaque, we can just use it directly.
302 // Otherwise we create a new type and resolve its body later. This will be
303 // resolved by the top level of get().
304 DefinitionsToResolve.push_back(STy);
305 return *Entry = StructType::create(STy->getContext());
310 //===----------------------------------------------------------------------===//
311 // ModuleLinker implementation.
312 //===----------------------------------------------------------------------===//
315 /// ModuleLinker - This is an implementation class for the LinkModules
316 /// function, which is the entrypoint for this file.
322 /// ValueMap - Mapping of values from what they used to be in Src, to what
323 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
324 /// some overhead due to the use of Value handles which the Linker doesn't
325 /// actually need, but this allows us to reuse the ValueMapper code.
326 ValueToValueMapTy ValueMap;
328 struct AppendingVarInfo {
329 GlobalVariable *NewGV; // New aggregate global in dest module.
330 Constant *DstInit; // Old initializer from dest module.
331 Constant *SrcInit; // Old initializer from src module.
334 std::vector<AppendingVarInfo> AppendingVars;
337 std::string ErrorMsg;
339 ModuleLinker(Module *dstM, Module *srcM) : DstM(dstM), SrcM(srcM) { }
344 /// emitError - Helper method for setting a message and returning an error
346 bool emitError(const Twine &Message) {
347 ErrorMsg = Message.str();
351 /// getLinkageResult - This analyzes the two global values and determines
352 /// what the result will look like in the destination module.
353 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
354 GlobalValue::LinkageTypes <, bool &LinkFromSrc);
356 /// getLinkedToGlobal - Given a global in the source module, return the
357 /// global in the destination module that is being linked to, if any.
358 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
359 // If the source has no name it can't link. If it has local linkage,
360 // there is no name match-up going on.
361 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
364 // Otherwise see if we have a match in the destination module's symtab.
365 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
366 if (DGV == 0) return 0;
368 // If we found a global with the same name in the dest module, but it has
369 // internal linkage, we are really not doing any linkage here.
370 if (DGV->hasLocalLinkage())
373 // Otherwise, we do in fact link to the destination global.
377 void computeTypeMapping();
379 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
380 bool linkGlobalProto(GlobalVariable *SrcGV);
381 bool linkFunctionProto(Function *SrcF);
382 bool linkAliasProto(GlobalAlias *SrcA);
384 void linkAppendingVarInit(const AppendingVarInfo &AVI);
385 void linkGlobalInits();
386 void linkFunctionBody(Function *Dst, Function *Src);
387 void linkAliasBodies();
388 void linkNamedMDNodes();
394 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
395 /// in the symbol table. This is good for all clients except for us. Go
396 /// through the trouble to force this back.
397 static void forceRenaming(GlobalValue *GV, StringRef Name) {
398 // If the global doesn't force its name or if it already has the right name,
399 // there is nothing for us to do.
400 if (GV->hasLocalLinkage() || GV->getName() == Name)
403 Module *M = GV->getParent();
405 // If there is a conflict, rename the conflict.
406 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
407 GV->takeName(ConflictGV);
408 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
409 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
411 GV->setName(Name); // Force the name back
415 /// CopyGVAttributes - copy additional attributes (those not needed to construct
416 /// a GlobalValue) from the SrcGV to the DestGV.
417 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
418 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
419 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
420 DestGV->copyAttributesFrom(SrcGV);
421 DestGV->setAlignment(Alignment);
423 forceRenaming(DestGV, SrcGV->getName());
426 /// getLinkageResult - This analyzes the two global values and determines what
427 /// the result will look like in the destination module. In particular, it
428 /// computes the resultant linkage type, computes whether the global in the
429 /// source should be copied over to the destination (replacing the existing
430 /// one), and computes whether this linkage is an error or not. It also performs
431 /// visibility checks: we cannot link together two symbols with different
433 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
434 GlobalValue::LinkageTypes <,
436 assert(Dest && "Must have two globals being queried");
437 assert(!Src->hasLocalLinkage() &&
438 "If Src has internal linkage, Dest shouldn't be set!");
440 bool SrcIsDeclaration = Src->isDeclaration();
441 bool DestIsDeclaration = Dest->isDeclaration();
443 if (SrcIsDeclaration) {
444 // If Src is external or if both Src & Dest are external.. Just link the
445 // external globals, we aren't adding anything.
446 if (Src->hasDLLImportLinkage()) {
447 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
448 if (DestIsDeclaration) {
450 LT = Src->getLinkage();
452 } else if (Dest->hasExternalWeakLinkage()) {
453 // If the Dest is weak, use the source linkage.
455 LT = Src->getLinkage();
458 LT = Dest->getLinkage();
460 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
461 // If Dest is external but Src is not:
463 LT = Src->getLinkage();
464 } else if (Src->isWeakForLinker()) {
465 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
467 if (Dest->hasExternalWeakLinkage() ||
468 Dest->hasAvailableExternallyLinkage() ||
469 (Dest->hasLinkOnceLinkage() &&
470 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
472 LT = Src->getLinkage();
475 LT = Dest->getLinkage();
477 } else if (Dest->isWeakForLinker()) {
478 // At this point we know that Src has External* or DLL* linkage.
479 if (Src->hasExternalWeakLinkage()) {
481 LT = Dest->getLinkage();
484 LT = GlobalValue::ExternalLinkage;
487 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
488 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
489 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
490 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
491 "Unexpected linkage type!");
492 return emitError("Linking globals named '" + Src->getName() +
493 "': symbol multiply defined!");
497 if (Src->getVisibility() != Dest->getVisibility() &&
498 !SrcIsDeclaration && !DestIsDeclaration &&
499 !Src->hasAvailableExternallyLinkage() &&
500 !Dest->hasAvailableExternallyLinkage())
501 return emitError("Linking globals named '" + Src->getName() +
502 "': symbols have different visibilities!");
506 /// computeTypeMapping - Loop over all of the linked values to compute type
507 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
508 /// we have two struct types 'Foo' but one got renamed when the module was
509 /// loaded into the same LLVMContext.
510 void ModuleLinker::computeTypeMapping() {
511 // Incorporate globals.
512 for (Module::global_iterator I = SrcM->global_begin(),
513 E = SrcM->global_end(); I != E; ++I) {
514 GlobalValue *DGV = getLinkedToGlobal(I);
515 if (DGV == 0) continue;
517 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
518 TypeMap.addTypeMapping(DGV->getType(), I->getType());
522 // Unify the element type of appending arrays.
523 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
524 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
525 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
528 // Incorporate functions.
529 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
530 if (GlobalValue *DGV = getLinkedToGlobal(I))
531 TypeMap.addTypeMapping(DGV->getType(), I->getType());
534 // Don't bother incorporating aliases, they aren't generally typed well.
536 // Now that we have discovered all of the type equivalences, get a body for
537 // any 'opaque' types in the dest module that are now resolved.
538 TypeMap.linkDefinedTypeBodies();
541 /// linkAppendingVarProto - If there were any appending global variables, link
542 /// them together now. Return true on error.
543 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
544 GlobalVariable *SrcGV) {
546 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
547 return emitError("Linking globals named '" + SrcGV->getName() +
548 "': can only link appending global with another appending global!");
550 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
552 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
553 Type *EltTy = DstTy->getElementType();
555 // Check to see that they two arrays agree on type.
556 if (EltTy != SrcTy->getElementType())
557 return emitError("Appending variables with different element types!");
558 if (DstGV->isConstant() != SrcGV->isConstant())
559 return emitError("Appending variables linked with different const'ness!");
561 if (DstGV->getAlignment() != SrcGV->getAlignment())
563 "Appending variables with different alignment need to be linked!");
565 if (DstGV->getVisibility() != SrcGV->getVisibility())
567 "Appending variables with different visibility need to be linked!");
569 if (DstGV->getSection() != SrcGV->getSection())
571 "Appending variables with different section name need to be linked!");
573 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
574 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
576 // Create the new global variable.
578 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
579 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
580 DstGV->isThreadLocal(),
581 DstGV->getType()->getAddressSpace());
583 // Propagate alignment, visibility and section info.
584 CopyGVAttributes(NG, DstGV);
586 AppendingVarInfo AVI;
588 AVI.DstInit = DstGV->getInitializer();
589 AVI.SrcInit = SrcGV->getInitializer();
590 AppendingVars.push_back(AVI);
592 // Replace any uses of the two global variables with uses of the new
594 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
596 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
597 DstGV->eraseFromParent();
599 // Zap the initializer in the source variable so we don't try to link it.
600 SrcGV->setInitializer(0);
601 SrcGV->setLinkage(GlobalValue::ExternalLinkage);
605 /// linkGlobalProto - Loop through the global variables in the src module and
606 /// merge them into the dest module.
607 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
608 GlobalValue *DGV = getLinkedToGlobal(SGV);
611 // Concatenation of appending linkage variables is magic and handled later.
612 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
613 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
615 // Determine whether linkage of these two globals follows the source
616 // module's definition or the destination module's definition.
617 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
618 bool LinkFromSrc = false;
619 if (getLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc))
622 // If we're not linking from the source, then keep the definition that we
625 // Special case for const propagation.
626 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
627 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
628 DGVar->setConstant(true);
630 // Set calculated linkage.
631 DGV->setLinkage(NewLinkage);
633 // Make sure to remember this mapping.
634 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
636 // Destroy the source global's initializer (and convert it to a prototype)
637 // so that we don't attempt to copy it over when processing global
639 SGV->setInitializer(0);
640 SGV->setLinkage(GlobalValue::ExternalLinkage);
645 // No linking to be performed or linking from the source: simply create an
646 // identical version of the symbol over in the dest module... the
647 // initializer will be filled in later by LinkGlobalInits.
648 GlobalVariable *NewDGV =
649 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
650 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
651 SGV->getName(), /*insertbefore*/0,
652 SGV->isThreadLocal(),
653 SGV->getType()->getAddressSpace());
654 // Propagate alignment, visibility and section info.
655 CopyGVAttributes(NewDGV, SGV);
658 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
659 DGV->eraseFromParent();
662 // Make sure to remember this mapping.
663 ValueMap[SGV] = NewDGV;
667 /// linkFunctionProto - Link the function in the source module into the
668 /// destination module if needed, setting up mapping information.
669 bool ModuleLinker::linkFunctionProto(Function *SF) {
670 GlobalValue *DGV = getLinkedToGlobal(SF);
673 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
674 bool LinkFromSrc = false;
675 if (getLinkageResult(DGV, SF, NewLinkage, LinkFromSrc))
679 // Set calculated linkage
680 DGV->setLinkage(NewLinkage);
682 // Make sure to remember this mapping.
683 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
685 // Remove the body from the source module so we don't attempt to remap it.
691 // If there is no linkage to be performed or we are linking from the source,
693 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
694 SF->getLinkage(), SF->getName(), DstM);
695 CopyGVAttributes(NewDF, SF);
698 // Any uses of DF need to change to NewDF, with cast.
699 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
700 DGV->eraseFromParent();
703 ValueMap[SF] = NewDF;
707 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
709 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
710 GlobalValue *DGV = getLinkedToGlobal(SGA);
713 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
714 bool LinkFromSrc = false;
715 if (getLinkageResult(DGV, SGA, NewLinkage, LinkFromSrc))
719 // Set calculated linkage.
720 DGV->setLinkage(NewLinkage);
722 // Make sure to remember this mapping.
723 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
725 // Remove the body from the source module so we don't attempt to remap it.
731 // If there is no linkage to be performed or we're linking from the source,
733 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
734 SGA->getLinkage(), SGA->getName(),
736 CopyGVAttributes(NewDA, SGA);
739 // Any uses of DGV need to change to NewDA, with cast.
740 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
741 DGV->eraseFromParent();
744 ValueMap[SGA] = NewDA;
748 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
749 // Merge the initializer.
750 SmallVector<Constant*, 16> Elements;
751 if (ConstantArray *I = dyn_cast<ConstantArray>(AVI.DstInit)) {
752 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
753 Elements.push_back(I->getOperand(i));
755 assert(isa<ConstantAggregateZero>(AVI.DstInit));
756 ArrayType *DstAT = cast<ArrayType>(AVI.DstInit->getType());
757 Type *EltTy = DstAT->getElementType();
758 Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy));
761 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
762 if (const ConstantArray *I = dyn_cast<ConstantArray>(SrcInit)) {
763 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
764 Elements.push_back(I->getOperand(i));
766 assert(isa<ConstantAggregateZero>(SrcInit));
767 ArrayType *SrcAT = cast<ArrayType>(SrcInit->getType());
768 Type *EltTy = SrcAT->getElementType();
769 Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy));
771 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
772 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
776 // linkGlobalInits - Update the initializers in the Dest module now that all
777 // globals that may be referenced are in Dest.
778 void ModuleLinker::linkGlobalInits() {
779 // Loop over all of the globals in the src module, mapping them over as we go
780 for (Module::const_global_iterator I = SrcM->global_begin(),
781 E = SrcM->global_end(); I != E; ++I) {
782 if (!I->hasInitializer()) continue; // Only process initialized GV's.
784 // Grab destination global variable.
785 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
786 // Figure out what the initializer looks like in the dest module.
787 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
792 // linkFunctionBody - Copy the source function over into the dest function and
793 // fix up references to values. At this point we know that Dest is an external
794 // function, and that Src is not.
795 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
796 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
798 // Go through and convert function arguments over, remembering the mapping.
799 Function::arg_iterator DI = Dst->arg_begin();
800 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
802 DI->setName(I->getName()); // Copy the name over.
804 // Add a mapping to our mapping.
808 // Splice the body of the source function into the dest function.
809 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
811 // At this point, all of the instructions and values of the function are now
812 // copied over. The only problem is that they are still referencing values in
813 // the Source function as operands. Loop through all of the operands of the
814 // functions and patch them up to point to the local versions.
815 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
816 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
817 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
819 // There is no need to map the arguments anymore.
820 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
826 void ModuleLinker::linkAliasBodies() {
827 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
829 if (Constant *Aliasee = I->getAliasee()) {
830 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
831 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
835 /// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
837 void ModuleLinker::linkNamedMDNodes() {
838 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
839 E = SrcM->named_metadata_end(); I != E; ++I) {
840 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
841 // Add Src elements into Dest node.
842 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
843 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
848 bool ModuleLinker::run() {
849 assert(DstM && "Null Destination module");
850 assert(SrcM && "Null Source Module");
852 // Inherit the target data from the source module if the destination module
853 // doesn't have one already.
854 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
855 DstM->setDataLayout(SrcM->getDataLayout());
857 // Copy the target triple from the source to dest if the dest's is empty.
858 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
859 DstM->setTargetTriple(SrcM->getTargetTriple());
861 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
862 SrcM->getDataLayout() != DstM->getDataLayout())
863 errs() << "WARNING: Linking two modules of different data layouts!\n";
864 if (!SrcM->getTargetTriple().empty() &&
865 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
866 errs() << "WARNING: Linking two modules of different target triples: ";
867 if (!SrcM->getModuleIdentifier().empty())
868 errs() << SrcM->getModuleIdentifier() << ": ";
869 errs() << "'" << SrcM->getTargetTriple() << "' and '"
870 << DstM->getTargetTriple() << "'\n";
873 // Append the module inline asm string.
874 if (!SrcM->getModuleInlineAsm().empty()) {
875 if (DstM->getModuleInlineAsm().empty())
876 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
878 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
879 SrcM->getModuleInlineAsm());
882 // Update the destination module's dependent libraries list with the libraries
883 // from the source module. There's no opportunity for duplicates here as the
884 // Module ensures that duplicate insertions are discarded.
885 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
887 DstM->addLibrary(*SI);
889 // If the source library's module id is in the dependent library list of the
890 // destination library, remove it since that module is now linked in.
891 StringRef ModuleId = SrcM->getModuleIdentifier();
892 if (!ModuleId.empty())
893 DstM->removeLibrary(sys::path::stem(ModuleId));
896 // Loop over all of the linked values to compute type mappings.
897 computeTypeMapping();
899 // Insert all of the globals in src into the DstM module... without linking
900 // initializers (which could refer to functions not yet mapped over).
901 for (Module::global_iterator I = SrcM->global_begin(),
902 E = SrcM->global_end(); I != E; ++I)
903 if (linkGlobalProto(I))
906 // Link the functions together between the two modules, without doing function
907 // bodies... this just adds external function prototypes to the DstM
908 // function... We do this so that when we begin processing function bodies,
909 // all of the global values that may be referenced are available in our
911 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
912 if (linkFunctionProto(I))
915 // If there were any aliases, link them now.
916 for (Module::alias_iterator I = SrcM->alias_begin(),
917 E = SrcM->alias_end(); I != E; ++I)
918 if (linkAliasProto(I))
921 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
922 linkAppendingVarInit(AppendingVars[i]);
924 // Update the initializers in the DstM module now that all globals that may
925 // be referenced are in DstM.
928 // Link in the function bodies that are defined in the source module into
930 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
931 if (SF->isDeclaration()) continue; // No body if function is external.
933 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
936 // Resolve all uses of aliases with aliasees.
939 // Remap all of the named mdnoes in Src into the DstM module. We do this
940 // after linking GlobalValues so that MDNodes that reference GlobalValues
941 // are properly remapped.
944 // Now that all of the types from the source are used, resolve any structs
945 // copied over to the dest that didn't exist there.
946 TypeMap.linkDefinedTypeBodies();
951 //===----------------------------------------------------------------------===//
952 // LinkModules entrypoint.
953 //===----------------------------------------------------------------------===//
955 // LinkModules - This function links two modules together, with the resulting
956 // left module modified to be the composite of the two input modules. If an
957 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
958 // the problem. Upon failure, the Dest module could be in a modified state, and
959 // shouldn't be relied on to be consistent.
960 bool Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
961 ModuleLinker TheLinker(Dest, Src);
962 if (TheLinker.run()) {
963 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;