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/DenseSet.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/TypeFinder.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/ValueMapper.h"
33 //===----------------------------------------------------------------------===//
34 // TypeMap implementation.
35 //===----------------------------------------------------------------------===//
38 class TypeMapTy : public ValueMapTypeRemapper {
39 /// MappedTypes - This is a mapping from a source type to a destination type
41 DenseMap<Type*, Type*> MappedTypes;
43 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
44 /// we speculatively add types to MappedTypes, but keep track of them here in
45 /// case we need to roll back.
46 SmallVector<Type*, 16> SpeculativeTypes;
48 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
49 /// source module that are mapped to an opaque struct in the destination
51 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
53 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
54 /// destination modules who are getting a body from the source module.
55 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
58 /// addTypeMapping - Indicate that the specified type in the destination
59 /// module is conceptually equivalent to the specified type in the source
61 void addTypeMapping(Type *DstTy, Type *SrcTy);
63 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
64 /// module from a type definition in the source module.
65 void linkDefinedTypeBodies();
67 /// get - Return the mapped type to use for the specified input type from the
69 Type *get(Type *SrcTy);
71 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
73 /// dump - Dump out the type map for debugging purposes.
75 for (DenseMap<Type*, Type*>::const_iterator
76 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
77 dbgs() << "TypeMap: ";
86 Type *getImpl(Type *T);
87 /// remapType - Implement the ValueMapTypeRemapper interface.
88 Type *remapType(Type *SrcTy) {
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 Type *&Entry = MappedTypes[SrcTy];
100 if (DstTy == SrcTy) {
105 // Check to see if these types are recursively isomorphic and establish a
106 // mapping between them if so.
107 if (!areTypesIsomorphic(DstTy, SrcTy)) {
108 // Oops, they aren't isomorphic. Just discard this request by rolling out
109 // any speculative mappings we've established.
110 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
111 MappedTypes.erase(SpeculativeTypes[i]);
113 SpeculativeTypes.clear();
116 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
117 /// if they are isomorphic, false if they are not.
118 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
119 // Two types with differing kinds are clearly not isomorphic.
120 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
122 // If we have an entry in the MappedTypes table, then we have our answer.
123 Type *&Entry = MappedTypes[SrcTy];
125 return Entry == DstTy;
127 // Two identical types are clearly isomorphic. Remember this
128 // non-speculatively.
129 if (DstTy == SrcTy) {
134 // Okay, we have two types with identical kinds that we haven't seen before.
136 // If this is an opaque struct type, special case it.
137 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
138 // Mapping an opaque type to any struct, just keep the dest struct.
139 if (SSTy->isOpaque()) {
141 SpeculativeTypes.push_back(SrcTy);
145 // Mapping a non-opaque source type to an opaque dest. If this is the first
146 // type that we're mapping onto this destination type then we succeed. Keep
147 // the dest, but fill it in later. This doesn't need to be speculative. If
148 // this is the second (different) type that we're trying to map onto the
149 // same opaque type then we fail.
150 if (cast<StructType>(DstTy)->isOpaque()) {
151 // We can only map one source type onto the opaque destination type.
152 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
154 SrcDefinitionsToResolve.push_back(SSTy);
160 // If the number of subtypes disagree between the two types, then we fail.
161 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
164 // Fail if any of the extra properties (e.g. array size) of the type disagree.
165 if (isa<IntegerType>(DstTy))
166 return false; // bitwidth disagrees.
167 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
168 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
171 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
172 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
174 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
175 StructType *SSTy = cast<StructType>(SrcTy);
176 if (DSTy->isLiteral() != SSTy->isLiteral() ||
177 DSTy->isPacked() != SSTy->isPacked())
179 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
180 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
182 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
183 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
187 // Otherwise, we speculate that these two types will line up and recursively
188 // check the subelements.
190 SpeculativeTypes.push_back(SrcTy);
192 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
193 if (!areTypesIsomorphic(DstTy->getContainedType(i),
194 SrcTy->getContainedType(i)))
197 // If everything seems to have lined up, then everything is great.
201 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
202 /// module from a type definition in the source module.
203 void TypeMapTy::linkDefinedTypeBodies() {
204 SmallVector<Type*, 16> Elements;
205 SmallString<16> TmpName;
207 // Note that processing entries in this loop (calling 'get') can add new
208 // entries to the SrcDefinitionsToResolve vector.
209 while (!SrcDefinitionsToResolve.empty()) {
210 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
211 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
213 // TypeMap is a many-to-one mapping, if there were multiple types that
214 // provide a body for DstSTy then previous iterations of this loop may have
215 // already handled it. Just ignore this case.
216 if (!DstSTy->isOpaque()) continue;
217 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
219 // Map the body of the source type over to a new body for the dest type.
220 Elements.resize(SrcSTy->getNumElements());
221 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
222 Elements[i] = getImpl(SrcSTy->getElementType(i));
224 DstSTy->setBody(Elements, SrcSTy->isPacked());
226 // If DstSTy has no name or has a longer name than STy, then viciously steal
228 if (!SrcSTy->hasName()) continue;
229 StringRef SrcName = SrcSTy->getName();
231 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
232 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
234 DstSTy->setName(TmpName.str());
239 DstResolvedOpaqueTypes.clear();
242 /// get - Return the mapped type to use for the specified input type from the
244 Type *TypeMapTy::get(Type *Ty) {
245 Type *Result = getImpl(Ty);
247 // If this caused a reference to any struct type, resolve it before returning.
248 if (!SrcDefinitionsToResolve.empty())
249 linkDefinedTypeBodies();
253 /// getImpl - This is the recursive version of get().
254 Type *TypeMapTy::getImpl(Type *Ty) {
255 // If we already have an entry for this type, return it.
256 Type **Entry = &MappedTypes[Ty];
257 if (*Entry) return *Entry;
259 // If this is not a named struct type, then just map all of the elements and
260 // then rebuild the type from inside out.
261 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
262 // If there are no element types to map, then the type is itself. This is
263 // true for the anonymous {} struct, things like 'float', integers, etc.
264 if (Ty->getNumContainedTypes() == 0)
267 // Remap all of the elements, keeping track of whether any of them change.
268 bool AnyChange = false;
269 SmallVector<Type*, 4> ElementTypes;
270 ElementTypes.resize(Ty->getNumContainedTypes());
271 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
272 ElementTypes[i] = getImpl(Ty->getContainedType(i));
273 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
276 // If we found our type while recursively processing stuff, just use it.
277 Entry = &MappedTypes[Ty];
278 if (*Entry) return *Entry;
280 // If all of the element types mapped directly over, then the type is usable
285 // Otherwise, rebuild a modified type.
286 switch (Ty->getTypeID()) {
287 default: llvm_unreachable("unknown derived type to remap");
288 case Type::ArrayTyID:
289 return *Entry = ArrayType::get(ElementTypes[0],
290 cast<ArrayType>(Ty)->getNumElements());
291 case Type::VectorTyID:
292 return *Entry = VectorType::get(ElementTypes[0],
293 cast<VectorType>(Ty)->getNumElements());
294 case Type::PointerTyID:
295 return *Entry = PointerType::get(ElementTypes[0],
296 cast<PointerType>(Ty)->getAddressSpace());
297 case Type::FunctionTyID:
298 return *Entry = FunctionType::get(ElementTypes[0],
299 makeArrayRef(ElementTypes).slice(1),
300 cast<FunctionType>(Ty)->isVarArg());
301 case Type::StructTyID:
302 // Note that this is only reached for anonymous structs.
303 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
304 cast<StructType>(Ty)->isPacked());
308 // Otherwise, this is an unmapped named struct. If the struct can be directly
309 // mapped over, just use it as-is. This happens in a case when the linked-in
310 // module has something like:
311 // %T = type {%T*, i32}
312 // @GV = global %T* null
313 // where T does not exist at all in the destination module.
315 // The other case we watch for is when the type is not in the destination
316 // module, but that it has to be rebuilt because it refers to something that
317 // is already mapped. For example, if the destination module has:
319 // and the source module has something like
320 // %A' = type { i32 }
321 // %B = type { %A'* }
322 // @GV = global %B* null
323 // then we want to create a new type: "%B = type { %A*}" and have it take the
324 // pristine "%B" name from the source module.
326 // To determine which case this is, we have to recursively walk the type graph
327 // speculating that we'll be able to reuse it unmodified. Only if this is
328 // safe would we map the entire thing over. Because this is an optimization,
329 // and is not required for the prettiness of the linked module, we just skip
330 // it and always rebuild a type here.
331 StructType *STy = cast<StructType>(Ty);
333 // If the type is opaque, we can just use it directly.
337 // Otherwise we create a new type and resolve its body later. This will be
338 // resolved by the top level of get().
339 SrcDefinitionsToResolve.push_back(STy);
340 StructType *DTy = StructType::create(STy->getContext());
341 DstResolvedOpaqueTypes.insert(DTy);
345 //===----------------------------------------------------------------------===//
346 // ModuleLinker implementation.
347 //===----------------------------------------------------------------------===//
350 /// ModuleLinker - This is an implementation class for the LinkModules
351 /// function, which is the entrypoint for this file.
357 /// ValueMap - Mapping of values from what they used to be in Src, to what
358 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
359 /// some overhead due to the use of Value handles which the Linker doesn't
360 /// actually need, but this allows us to reuse the ValueMapper code.
361 ValueToValueMapTy ValueMap;
363 struct AppendingVarInfo {
364 GlobalVariable *NewGV; // New aggregate global in dest module.
365 Constant *DstInit; // Old initializer from dest module.
366 Constant *SrcInit; // Old initializer from src module.
369 std::vector<AppendingVarInfo> AppendingVars;
371 unsigned Mode; // Mode to treat source module.
373 // Set of items not to link in from source.
374 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
376 // Vector of functions to lazily link in.
377 std::vector<Function*> LazilyLinkFunctions;
380 std::string ErrorMsg;
382 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
383 : DstM(dstM), SrcM(srcM), Mode(mode) { }
388 /// emitError - Helper method for setting a message and returning an error
390 bool emitError(const Twine &Message) {
391 ErrorMsg = Message.str();
395 /// getLinkageResult - This analyzes the two global values and determines
396 /// what the result will look like in the destination module.
397 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
398 GlobalValue::LinkageTypes <,
399 GlobalValue::VisibilityTypes &Vis,
402 /// getLinkedToGlobal - Given a global in the source module, return the
403 /// global in the destination module that is being linked to, if any.
404 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
405 // If the source has no name it can't link. If it has local linkage,
406 // there is no name match-up going on.
407 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
410 // Otherwise see if we have a match in the destination module's symtab.
411 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
412 if (DGV == 0) return 0;
414 // If we found a global with the same name in the dest module, but it has
415 // internal linkage, we are really not doing any linkage here.
416 if (DGV->hasLocalLinkage())
419 // Otherwise, we do in fact link to the destination global.
423 void computeTypeMapping();
425 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
426 bool linkGlobalProto(GlobalVariable *SrcGV);
427 bool linkFunctionProto(Function *SrcF);
428 bool linkAliasProto(GlobalAlias *SrcA);
429 bool linkModuleFlagsMetadata();
431 void linkAppendingVarInit(const AppendingVarInfo &AVI);
432 void linkGlobalInits();
433 void linkFunctionBody(Function *Dst, Function *Src);
434 void linkAliasBodies();
435 void linkNamedMDNodes();
439 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
440 /// in the symbol table. This is good for all clients except for us. Go
441 /// through the trouble to force this back.
442 static void forceRenaming(GlobalValue *GV, StringRef Name) {
443 // If the global doesn't force its name or if it already has the right name,
444 // there is nothing for us to do.
445 if (GV->hasLocalLinkage() || GV->getName() == Name)
448 Module *M = GV->getParent();
450 // If there is a conflict, rename the conflict.
451 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
452 GV->takeName(ConflictGV);
453 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
454 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
456 GV->setName(Name); // Force the name back
460 /// copyGVAttributes - copy additional attributes (those not needed to construct
461 /// a GlobalValue) from the SrcGV to the DestGV.
462 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
463 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
464 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
465 DestGV->copyAttributesFrom(SrcGV);
466 DestGV->setAlignment(Alignment);
468 forceRenaming(DestGV, SrcGV->getName());
471 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
472 GlobalValue::VisibilityTypes b) {
473 if (a == GlobalValue::HiddenVisibility)
475 if (b == GlobalValue::HiddenVisibility)
477 if (a == GlobalValue::ProtectedVisibility)
479 if (b == GlobalValue::ProtectedVisibility)
484 /// getLinkageResult - This analyzes the two global values and determines what
485 /// the result will look like in the destination module. In particular, it
486 /// computes the resultant linkage type and visibility, computes whether the
487 /// global in the source should be copied over to the destination (replacing
488 /// the existing one), and computes whether this linkage is an error or not.
489 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
490 GlobalValue::LinkageTypes <,
491 GlobalValue::VisibilityTypes &Vis,
493 assert(Dest && "Must have two globals being queried");
494 assert(!Src->hasLocalLinkage() &&
495 "If Src has internal linkage, Dest shouldn't be set!");
497 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
498 bool DestIsDeclaration = Dest->isDeclaration();
500 if (SrcIsDeclaration) {
501 // If Src is external or if both Src & Dest are external.. Just link the
502 // external globals, we aren't adding anything.
503 if (Src->hasDLLImportLinkage()) {
504 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
505 if (DestIsDeclaration) {
507 LT = Src->getLinkage();
509 } else if (Dest->hasExternalWeakLinkage()) {
510 // If the Dest is weak, use the source linkage.
512 LT = Src->getLinkage();
515 LT = Dest->getLinkage();
517 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
518 // If Dest is external but Src is not:
520 LT = Src->getLinkage();
521 } else if (Src->isWeakForLinker()) {
522 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
524 if (Dest->hasExternalWeakLinkage() ||
525 Dest->hasAvailableExternallyLinkage() ||
526 (Dest->hasLinkOnceLinkage() &&
527 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
529 LT = Src->getLinkage();
532 LT = Dest->getLinkage();
534 } else if (Dest->isWeakForLinker()) {
535 // At this point we know that Src has External* or DLL* linkage.
536 if (Src->hasExternalWeakLinkage()) {
538 LT = Dest->getLinkage();
541 LT = GlobalValue::ExternalLinkage;
544 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
545 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
546 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
547 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
548 "Unexpected linkage type!");
549 return emitError("Linking globals named '" + Src->getName() +
550 "': symbol multiply defined!");
553 // Compute the visibility. We follow the rules in the System V Application
555 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
556 Dest->getVisibility() : Src->getVisibility();
560 /// computeTypeMapping - Loop over all of the linked values to compute type
561 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
562 /// we have two struct types 'Foo' but one got renamed when the module was
563 /// loaded into the same LLVMContext.
564 void ModuleLinker::computeTypeMapping() {
565 // Incorporate globals.
566 for (Module::global_iterator I = SrcM->global_begin(),
567 E = SrcM->global_end(); I != E; ++I) {
568 GlobalValue *DGV = getLinkedToGlobal(I);
569 if (DGV == 0) continue;
571 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
572 TypeMap.addTypeMapping(DGV->getType(), I->getType());
576 // Unify the element type of appending arrays.
577 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
578 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
579 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
582 // Incorporate functions.
583 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
584 if (GlobalValue *DGV = getLinkedToGlobal(I))
585 TypeMap.addTypeMapping(DGV->getType(), I->getType());
588 // Incorporate types by name, scanning all the types in the source module.
589 // At this point, the destination module may have a type "%foo = { i32 }" for
590 // example. When the source module got loaded into the same LLVMContext, if
591 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
592 TypeFinder SrcStructTypes;
593 SrcStructTypes.run(*SrcM, true);
594 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
595 SrcStructTypes.end());
597 TypeFinder DstStructTypes;
598 DstStructTypes.run(*DstM, true);
599 SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
600 DstStructTypes.end());
602 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
603 StructType *ST = SrcStructTypes[i];
604 if (!ST->hasName()) continue;
606 // Check to see if there is a dot in the name followed by a digit.
607 size_t DotPos = ST->getName().rfind('.');
608 if (DotPos == 0 || DotPos == StringRef::npos ||
609 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
612 // Check to see if the destination module has a struct with the prefix name.
613 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
614 // Don't use it if this actually came from the source module. They're in
615 // the same LLVMContext after all. Also don't use it unless the type is
616 // actually used in the destination module. This can happen in situations
621 // %Z = type { %A } %B = type { %C.1 }
622 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
623 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
624 // %C = type { i8* } %B.3 = type { %C.1 }
626 // When we link Module B with Module A, the '%B' in Module B is
627 // used. However, that would then use '%C.1'. But when we process '%C.1',
628 // we prefer to take the '%C' version. So we are then left with both
629 // '%C.1' and '%C' being used for the same types. This leads to some
630 // variables using one type and some using the other.
631 if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
632 TypeMap.addTypeMapping(DST, ST);
635 // Don't bother incorporating aliases, they aren't generally typed well.
637 // Now that we have discovered all of the type equivalences, get a body for
638 // any 'opaque' types in the dest module that are now resolved.
639 TypeMap.linkDefinedTypeBodies();
642 /// linkAppendingVarProto - If there were any appending global variables, link
643 /// them together now. Return true on error.
644 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
645 GlobalVariable *SrcGV) {
647 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
648 return emitError("Linking globals named '" + SrcGV->getName() +
649 "': can only link appending global with another appending global!");
651 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
653 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
654 Type *EltTy = DstTy->getElementType();
656 // Check to see that they two arrays agree on type.
657 if (EltTy != SrcTy->getElementType())
658 return emitError("Appending variables with different element types!");
659 if (DstGV->isConstant() != SrcGV->isConstant())
660 return emitError("Appending variables linked with different const'ness!");
662 if (DstGV->getAlignment() != SrcGV->getAlignment())
664 "Appending variables with different alignment need to be linked!");
666 if (DstGV->getVisibility() != SrcGV->getVisibility())
668 "Appending variables with different visibility need to be linked!");
670 if (DstGV->getSection() != SrcGV->getSection())
672 "Appending variables with different section name need to be linked!");
674 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
675 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
677 // Create the new global variable.
679 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
680 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
681 DstGV->getThreadLocalMode(),
682 DstGV->getType()->getAddressSpace());
684 // Propagate alignment, visibility and section info.
685 copyGVAttributes(NG, DstGV);
687 AppendingVarInfo AVI;
689 AVI.DstInit = DstGV->getInitializer();
690 AVI.SrcInit = SrcGV->getInitializer();
691 AppendingVars.push_back(AVI);
693 // Replace any uses of the two global variables with uses of the new
695 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
697 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
698 DstGV->eraseFromParent();
700 // Track the source variable so we don't try to link it.
701 DoNotLinkFromSource.insert(SrcGV);
706 /// linkGlobalProto - Loop through the global variables in the src module and
707 /// merge them into the dest module.
708 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
709 GlobalValue *DGV = getLinkedToGlobal(SGV);
710 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
713 // Concatenation of appending linkage variables is magic and handled later.
714 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
715 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
717 // Determine whether linkage of these two globals follows the source
718 // module's definition or the destination module's definition.
719 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
720 GlobalValue::VisibilityTypes NV;
721 bool LinkFromSrc = false;
722 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
726 // If we're not linking from the source, then keep the definition that we
729 // Special case for const propagation.
730 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
731 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
732 DGVar->setConstant(true);
734 // Set calculated linkage and visibility.
735 DGV->setLinkage(NewLinkage);
736 DGV->setVisibility(*NewVisibility);
738 // Make sure to remember this mapping.
739 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
741 // Track the source global so that we don't attempt to copy it over when
742 // processing global initializers.
743 DoNotLinkFromSource.insert(SGV);
749 // No linking to be performed or linking from the source: simply create an
750 // identical version of the symbol over in the dest module... the
751 // initializer will be filled in later by LinkGlobalInits.
752 GlobalVariable *NewDGV =
753 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
754 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
755 SGV->getName(), /*insertbefore*/0,
756 SGV->getThreadLocalMode(),
757 SGV->getType()->getAddressSpace());
758 // Propagate alignment, visibility and section info.
759 copyGVAttributes(NewDGV, SGV);
761 NewDGV->setVisibility(*NewVisibility);
764 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
765 DGV->eraseFromParent();
768 // Make sure to remember this mapping.
769 ValueMap[SGV] = NewDGV;
773 /// linkFunctionProto - Link the function in the source module into the
774 /// destination module if needed, setting up mapping information.
775 bool ModuleLinker::linkFunctionProto(Function *SF) {
776 GlobalValue *DGV = getLinkedToGlobal(SF);
777 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
780 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
781 bool LinkFromSrc = false;
782 GlobalValue::VisibilityTypes NV;
783 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
788 // Set calculated linkage
789 DGV->setLinkage(NewLinkage);
790 DGV->setVisibility(*NewVisibility);
792 // Make sure to remember this mapping.
793 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
795 // Track the function from the source module so we don't attempt to remap
797 DoNotLinkFromSource.insert(SF);
803 // If there is no linkage to be performed or we are linking from the source,
805 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
806 SF->getLinkage(), SF->getName(), DstM);
807 copyGVAttributes(NewDF, SF);
809 NewDF->setVisibility(*NewVisibility);
812 // Any uses of DF need to change to NewDF, with cast.
813 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
814 DGV->eraseFromParent();
816 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
817 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
818 SF->hasAvailableExternallyLinkage()) {
819 DoNotLinkFromSource.insert(SF);
820 LazilyLinkFunctions.push_back(SF);
824 ValueMap[SF] = NewDF;
828 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
830 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
831 GlobalValue *DGV = getLinkedToGlobal(SGA);
832 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
835 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
836 GlobalValue::VisibilityTypes NV;
837 bool LinkFromSrc = false;
838 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
843 // Set calculated linkage.
844 DGV->setLinkage(NewLinkage);
845 DGV->setVisibility(*NewVisibility);
847 // Make sure to remember this mapping.
848 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
850 // Track the alias from the source module so we don't attempt to remap it.
851 DoNotLinkFromSource.insert(SGA);
857 // If there is no linkage to be performed or we're linking from the source,
859 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
860 SGA->getLinkage(), SGA->getName(),
862 copyGVAttributes(NewDA, SGA);
864 NewDA->setVisibility(*NewVisibility);
867 // Any uses of DGV need to change to NewDA, with cast.
868 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
869 DGV->eraseFromParent();
872 ValueMap[SGA] = NewDA;
876 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
877 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
879 for (unsigned i = 0; i != NumElements; ++i)
880 Dest.push_back(C->getAggregateElement(i));
883 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
884 // Merge the initializer.
885 SmallVector<Constant*, 16> Elements;
886 getArrayElements(AVI.DstInit, Elements);
888 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
889 getArrayElements(SrcInit, Elements);
891 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
892 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
895 /// linkGlobalInits - Update the initializers in the Dest module now that all
896 /// globals that may be referenced are in Dest.
897 void ModuleLinker::linkGlobalInits() {
898 // Loop over all of the globals in the src module, mapping them over as we go
899 for (Module::const_global_iterator I = SrcM->global_begin(),
900 E = SrcM->global_end(); I != E; ++I) {
902 // Only process initialized GV's or ones not already in dest.
903 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
905 // Grab destination global variable.
906 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
907 // Figure out what the initializer looks like in the dest module.
908 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
913 /// linkFunctionBody - Copy the source function over into the dest function and
914 /// fix up references to values. At this point we know that Dest is an external
915 /// function, and that Src is not.
916 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
917 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
919 // Go through and convert function arguments over, remembering the mapping.
920 Function::arg_iterator DI = Dst->arg_begin();
921 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
923 DI->setName(I->getName()); // Copy the name over.
925 // Add a mapping to our mapping.
929 if (Mode == Linker::DestroySource) {
930 // Splice the body of the source function into the dest function.
931 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
933 // At this point, all of the instructions and values of the function are now
934 // copied over. The only problem is that they are still referencing values in
935 // the Source function as operands. Loop through all of the operands of the
936 // functions and patch them up to point to the local versions.
937 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
938 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
939 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
942 // Clone the body of the function into the dest function.
943 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
944 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
947 // There is no need to map the arguments anymore.
948 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
954 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
955 void ModuleLinker::linkAliasBodies() {
956 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
958 if (DoNotLinkFromSource.count(I))
960 if (Constant *Aliasee = I->getAliasee()) {
961 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
962 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
967 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
969 void ModuleLinker::linkNamedMDNodes() {
970 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
971 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
972 E = SrcM->named_metadata_end(); I != E; ++I) {
973 // Don't link module flags here. Do them separately.
974 if (&*I == SrcModFlags) continue;
975 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
976 // Add Src elements into Dest node.
977 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
978 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
983 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
985 bool ModuleLinker::linkModuleFlagsMetadata() {
986 // If the source module has no module flags, we are done.
987 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
988 if (!SrcModFlags) return false;
990 // If the destination module doesn't have module flags yet, then just copy
991 // over the source module's flags.
992 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
993 if (DstModFlags->getNumOperands() == 0) {
994 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
995 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1000 // First build a map of the existing module flags and requirements.
1001 DenseMap<MDString*, MDNode*> Flags;
1002 SmallSetVector<MDNode*, 16> Requirements;
1003 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1004 MDNode *Op = DstModFlags->getOperand(I);
1005 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1006 MDString *ID = cast<MDString>(Op->getOperand(1));
1008 if (Behavior->getZExtValue() == Module::Require) {
1009 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1015 // Merge in the flags from the source module, and also collect its set of
1017 bool HasErr = false;
1018 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1019 MDNode *SrcOp = SrcModFlags->getOperand(I);
1020 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1021 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1022 MDNode *DstOp = Flags.lookup(ID);
1023 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1025 // If this is a requirement, add it and continue.
1026 if (SrcBehaviorValue == Module::Require) {
1027 // If the destination module does not already have this requirement, add
1029 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1030 DstModFlags->addOperand(SrcOp);
1035 // If there is no existing flag with this ID, just add it.
1038 DstModFlags->addOperand(SrcOp);
1042 // Otherwise, perform a merge.
1043 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1044 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1046 // If either flag has override behavior, handle it first.
1047 if (DstBehaviorValue == Module::Override) {
1048 // Diagnose inconsistent flags which both have override behavior.
1049 if (SrcBehaviorValue == Module::Override &&
1050 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1051 HasErr |= emitError("linking module flags '" + ID->getString() +
1052 "': IDs have conflicting override values");
1055 } else if (SrcBehaviorValue == Module::Override) {
1056 // Update the destination flag to that of the source.
1057 DstOp->replaceOperandWith(0, SrcBehavior);
1058 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1062 // Diagnose inconsistent merge behavior types.
1063 if (SrcBehaviorValue != DstBehaviorValue) {
1064 HasErr |= emitError("linking module flags '" + ID->getString() +
1065 "': IDs have conflicting behaviors");
1069 // Perform the merge for standard behavior types.
1070 switch (SrcBehaviorValue) {
1071 case Module::Require:
1072 case Module::Override: assert(0 && "not possible"); break;
1073 case Module::Error: {
1074 // Emit an error if the values differ.
1075 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1076 HasErr |= emitError("linking module flags '" + ID->getString() +
1077 "': IDs have conflicting values");
1081 case Module::Warning: {
1082 // Emit a warning if the values differ.
1083 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1084 errs() << "WARNING: linking module flags '" << ID->getString()
1085 << "': IDs have conflicting values";
1089 case Module::Append: {
1090 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1091 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1092 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1093 Value **VP, **Values = VP = new Value*[NumOps];
1094 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1095 *VP = DstValue->getOperand(i);
1096 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1097 *VP = SrcValue->getOperand(i);
1098 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1099 ArrayRef<Value*>(Values,
1104 case Module::AppendUnique: {
1105 SmallSetVector<Value*, 16> Elts;
1106 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1107 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1108 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1109 Elts.insert(DstValue->getOperand(i));
1110 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1111 Elts.insert(SrcValue->getOperand(i));
1112 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1113 ArrayRef<Value*>(Elts.begin(),
1120 // Check all of the requirements.
1121 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1122 MDNode *Requirement = Requirements[I];
1123 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1124 Value *ReqValue = Requirement->getOperand(1);
1126 MDNode *Op = Flags[Flag];
1127 if (!Op || Op->getOperand(2) != ReqValue) {
1128 HasErr |= emitError("linking module flags '" + Flag->getString() +
1129 "': does not have the required value");
1137 bool ModuleLinker::run() {
1138 assert(DstM && "Null destination module");
1139 assert(SrcM && "Null source module");
1141 // Inherit the target data from the source module if the destination module
1142 // doesn't have one already.
1143 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1144 DstM->setDataLayout(SrcM->getDataLayout());
1146 // Copy the target triple from the source to dest if the dest's is empty.
1147 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1148 DstM->setTargetTriple(SrcM->getTargetTriple());
1150 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1151 SrcM->getDataLayout() != DstM->getDataLayout())
1152 errs() << "WARNING: Linking two modules of different data layouts!\n";
1153 if (!SrcM->getTargetTriple().empty() &&
1154 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1155 errs() << "WARNING: Linking two modules of different target triples: ";
1156 if (!SrcM->getModuleIdentifier().empty())
1157 errs() << SrcM->getModuleIdentifier() << ": ";
1158 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1159 << DstM->getTargetTriple() << "'\n";
1162 // Append the module inline asm string.
1163 if (!SrcM->getModuleInlineAsm().empty()) {
1164 if (DstM->getModuleInlineAsm().empty())
1165 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1167 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1168 SrcM->getModuleInlineAsm());
1171 // Loop over all of the linked values to compute type mappings.
1172 computeTypeMapping();
1174 // Insert all of the globals in src into the DstM module... without linking
1175 // initializers (which could refer to functions not yet mapped over).
1176 for (Module::global_iterator I = SrcM->global_begin(),
1177 E = SrcM->global_end(); I != E; ++I)
1178 if (linkGlobalProto(I))
1181 // Link the functions together between the two modules, without doing function
1182 // bodies... this just adds external function prototypes to the DstM
1183 // function... We do this so that when we begin processing function bodies,
1184 // all of the global values that may be referenced are available in our
1186 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1187 if (linkFunctionProto(I))
1190 // If there were any aliases, link them now.
1191 for (Module::alias_iterator I = SrcM->alias_begin(),
1192 E = SrcM->alias_end(); I != E; ++I)
1193 if (linkAliasProto(I))
1196 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1197 linkAppendingVarInit(AppendingVars[i]);
1199 // Update the initializers in the DstM module now that all globals that may
1200 // be referenced are in DstM.
1203 // Link in the function bodies that are defined in the source module into
1205 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1206 // Skip if not linking from source.
1207 if (DoNotLinkFromSource.count(SF)) continue;
1209 // Skip if no body (function is external) or materialize.
1210 if (SF->isDeclaration()) {
1211 if (!SF->isMaterializable())
1213 if (SF->Materialize(&ErrorMsg))
1217 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1218 SF->Dematerialize();
1221 // Resolve all uses of aliases with aliasees.
1224 // Remap all of the named MDNodes in Src into the DstM module. We do this
1225 // after linking GlobalValues so that MDNodes that reference GlobalValues
1226 // are properly remapped.
1229 // Merge the module flags into the DstM module.
1230 if (linkModuleFlagsMetadata())
1233 // Process vector of lazily linked in functions.
1234 bool LinkedInAnyFunctions;
1236 LinkedInAnyFunctions = false;
1238 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1239 E = LazilyLinkFunctions.end(); I != E; ++I) {
1244 Function *DF = cast<Function>(ValueMap[SF]);
1246 if (!DF->use_empty()) {
1248 // Materialize if necessary.
1249 if (SF->isDeclaration()) {
1250 if (!SF->isMaterializable())
1252 if (SF->Materialize(&ErrorMsg))
1256 // Link in function body.
1257 linkFunctionBody(DF, SF);
1258 SF->Dematerialize();
1260 // "Remove" from vector by setting the element to 0.
1263 // Set flag to indicate we may have more functions to lazily link in
1264 // since we linked in a function.
1265 LinkedInAnyFunctions = true;
1268 } while (LinkedInAnyFunctions);
1270 // Remove any prototypes of functions that were not actually linked in.
1271 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1272 E = LazilyLinkFunctions.end(); I != E; ++I) {
1277 Function *DF = cast<Function>(ValueMap[SF]);
1278 if (DF->use_empty())
1279 DF->eraseFromParent();
1282 // Now that all of the types from the source are used, resolve any structs
1283 // copied over to the dest that didn't exist there.
1284 TypeMap.linkDefinedTypeBodies();
1289 //===----------------------------------------------------------------------===//
1290 // LinkModules entrypoint.
1291 //===----------------------------------------------------------------------===//
1293 /// LinkModules - This function links two modules together, with the resulting
1294 /// left module modified to be the composite of the two input modules. If an
1295 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1296 /// the problem. Upon failure, the Dest module could be in a modified state,
1297 /// and shouldn't be relied on to be consistent.
1298 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1299 std::string *ErrorMsg) {
1300 ModuleLinker TheLinker(Dest, Src, Mode);
1301 if (TheLinker.run()) {
1302 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
1309 //===----------------------------------------------------------------------===//
1311 //===----------------------------------------------------------------------===//
1313 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1314 LLVMLinkerMode Mode, char **OutMessages) {
1315 std::string Messages;
1316 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1317 Mode, OutMessages? &Messages : 0);
1319 *OutMessages = strdup(Messages.c_str());