Move C++ code out of the C headers and into either C++ headers
[oota-llvm.git] / lib / Linker / LinkModules.cpp
1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM module linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Linker.h"
15 #include "llvm/Wrap.h"
16 #include "llvm-c/Linker.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/TypeFinder.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/Cloning.h"
30 #include "llvm/Transforms/Utils/ValueMapper.h"
31 #include <cctype>
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 // TypeMap implementation.
36 //===----------------------------------------------------------------------===//
37
38 namespace {
39 class TypeMapTy : public ValueMapTypeRemapper {
40   /// MappedTypes - This is a mapping from a source type to a destination type
41   /// to use.
42   DenseMap<Type*, Type*> MappedTypes;
43
44   /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
45   /// we speculatively add types to MappedTypes, but keep track of them here in
46   /// case we need to roll back.
47   SmallVector<Type*, 16> SpeculativeTypes;
48   
49   /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
50   /// source module that are mapped to an opaque struct in the destination
51   /// module.
52   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
53   
54   /// DstResolvedOpaqueTypes - This is the set of opaque types in the
55   /// destination modules who are getting a body from the source module.
56   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
57
58 public:
59   /// addTypeMapping - Indicate that the specified type in the destination
60   /// module is conceptually equivalent to the specified type in the source
61   /// module.
62   void addTypeMapping(Type *DstTy, Type *SrcTy);
63
64   /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
65   /// module from a type definition in the source module.
66   void linkDefinedTypeBodies();
67   
68   /// get - Return the mapped type to use for the specified input type from the
69   /// source module.
70   Type *get(Type *SrcTy);
71
72   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
73
74   /// dump - Dump out the type map for debugging purposes.
75   void dump() const {
76     for (DenseMap<Type*, Type*>::const_iterator
77            I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
78       dbgs() << "TypeMap: ";
79       I->first->dump();
80       dbgs() << " => ";
81       I->second->dump();
82       dbgs() << '\n';
83     }
84   }
85
86 private:
87   Type *getImpl(Type *T);
88   /// remapType - Implement the ValueMapTypeRemapper interface.
89   Type *remapType(Type *SrcTy) {
90     return get(SrcTy);
91   }
92   
93   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
94 };
95 }
96
97 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
98   Type *&Entry = MappedTypes[SrcTy];
99   if (Entry) return;
100   
101   if (DstTy == SrcTy) {
102     Entry = DstTy;
103     return;
104   }
105   
106   // Check to see if these types are recursively isomorphic and establish a
107   // mapping between them if so.
108   if (!areTypesIsomorphic(DstTy, SrcTy)) {
109     // Oops, they aren't isomorphic.  Just discard this request by rolling out
110     // any speculative mappings we've established.
111     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
112       MappedTypes.erase(SpeculativeTypes[i]);
113   }
114   SpeculativeTypes.clear();
115 }
116
117 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
118 /// if they are isomorphic, false if they are not.
119 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
120   // Two types with differing kinds are clearly not isomorphic.
121   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
122
123   // If we have an entry in the MappedTypes table, then we have our answer.
124   Type *&Entry = MappedTypes[SrcTy];
125   if (Entry)
126     return Entry == DstTy;
127
128   // Two identical types are clearly isomorphic.  Remember this
129   // non-speculatively.
130   if (DstTy == SrcTy) {
131     Entry = DstTy;
132     return true;
133   }
134   
135   // Okay, we have two types with identical kinds that we haven't seen before.
136
137   // If this is an opaque struct type, special case it.
138   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
139     // Mapping an opaque type to any struct, just keep the dest struct.
140     if (SSTy->isOpaque()) {
141       Entry = DstTy;
142       SpeculativeTypes.push_back(SrcTy);
143       return true;
144     }
145
146     // Mapping a non-opaque source type to an opaque dest.  If this is the first
147     // type that we're mapping onto this destination type then we succeed.  Keep
148     // the dest, but fill it in later.  This doesn't need to be speculative.  If
149     // this is the second (different) type that we're trying to map onto the
150     // same opaque type then we fail.
151     if (cast<StructType>(DstTy)->isOpaque()) {
152       // We can only map one source type onto the opaque destination type.
153       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
154         return false;
155       SrcDefinitionsToResolve.push_back(SSTy);
156       Entry = DstTy;
157       return true;
158     }
159   }
160   
161   // If the number of subtypes disagree between the two types, then we fail.
162   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
163     return false;
164   
165   // Fail if any of the extra properties (e.g. array size) of the type disagree.
166   if (isa<IntegerType>(DstTy))
167     return false;  // bitwidth disagrees.
168   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
169     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
170       return false;
171     
172   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
173     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
174       return false;
175   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
176     StructType *SSTy = cast<StructType>(SrcTy);
177     if (DSTy->isLiteral() != SSTy->isLiteral() ||
178         DSTy->isPacked() != SSTy->isPacked())
179       return false;
180   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
181     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
182       return false;
183   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
184     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
185       return false;
186   }
187
188   // Otherwise, we speculate that these two types will line up and recursively
189   // check the subelements.
190   Entry = DstTy;
191   SpeculativeTypes.push_back(SrcTy);
192
193   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
194     if (!areTypesIsomorphic(DstTy->getContainedType(i),
195                             SrcTy->getContainedType(i)))
196       return false;
197   
198   // If everything seems to have lined up, then everything is great.
199   return true;
200 }
201
202 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
203 /// module from a type definition in the source module.
204 void TypeMapTy::linkDefinedTypeBodies() {
205   SmallVector<Type*, 16> Elements;
206   SmallString<16> TmpName;
207   
208   // Note that processing entries in this loop (calling 'get') can add new
209   // entries to the SrcDefinitionsToResolve vector.
210   while (!SrcDefinitionsToResolve.empty()) {
211     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
212     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
213     
214     // TypeMap is a many-to-one mapping, if there were multiple types that
215     // provide a body for DstSTy then previous iterations of this loop may have
216     // already handled it.  Just ignore this case.
217     if (!DstSTy->isOpaque()) continue;
218     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
219     
220     // Map the body of the source type over to a new body for the dest type.
221     Elements.resize(SrcSTy->getNumElements());
222     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
223       Elements[i] = getImpl(SrcSTy->getElementType(i));
224     
225     DstSTy->setBody(Elements, SrcSTy->isPacked());
226     
227     // If DstSTy has no name or has a longer name than STy, then viciously steal
228     // STy's name.
229     if (!SrcSTy->hasName()) continue;
230     StringRef SrcName = SrcSTy->getName();
231     
232     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
233       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
234       SrcSTy->setName("");
235       DstSTy->setName(TmpName.str());
236       TmpName.clear();
237     }
238   }
239   
240   DstResolvedOpaqueTypes.clear();
241 }
242
243 /// get - Return the mapped type to use for the specified input type from the
244 /// source module.
245 Type *TypeMapTy::get(Type *Ty) {
246   Type *Result = getImpl(Ty);
247   
248   // If this caused a reference to any struct type, resolve it before returning.
249   if (!SrcDefinitionsToResolve.empty())
250     linkDefinedTypeBodies();
251   return Result;
252 }
253
254 /// getImpl - This is the recursive version of get().
255 Type *TypeMapTy::getImpl(Type *Ty) {
256   // If we already have an entry for this type, return it.
257   Type **Entry = &MappedTypes[Ty];
258   if (*Entry) return *Entry;
259   
260   // If this is not a named struct type, then just map all of the elements and
261   // then rebuild the type from inside out.
262   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
263     // If there are no element types to map, then the type is itself.  This is
264     // true for the anonymous {} struct, things like 'float', integers, etc.
265     if (Ty->getNumContainedTypes() == 0)
266       return *Entry = Ty;
267     
268     // Remap all of the elements, keeping track of whether any of them change.
269     bool AnyChange = false;
270     SmallVector<Type*, 4> ElementTypes;
271     ElementTypes.resize(Ty->getNumContainedTypes());
272     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
273       ElementTypes[i] = getImpl(Ty->getContainedType(i));
274       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
275     }
276     
277     // If we found our type while recursively processing stuff, just use it.
278     Entry = &MappedTypes[Ty];
279     if (*Entry) return *Entry;
280     
281     // If all of the element types mapped directly over, then the type is usable
282     // as-is.
283     if (!AnyChange)
284       return *Entry = Ty;
285     
286     // Otherwise, rebuild a modified type.
287     switch (Ty->getTypeID()) {
288     default: llvm_unreachable("unknown derived type to remap");
289     case Type::ArrayTyID:
290       return *Entry = ArrayType::get(ElementTypes[0],
291                                      cast<ArrayType>(Ty)->getNumElements());
292     case Type::VectorTyID: 
293       return *Entry = VectorType::get(ElementTypes[0],
294                                       cast<VectorType>(Ty)->getNumElements());
295     case Type::PointerTyID:
296       return *Entry = PointerType::get(ElementTypes[0],
297                                       cast<PointerType>(Ty)->getAddressSpace());
298     case Type::FunctionTyID:
299       return *Entry = FunctionType::get(ElementTypes[0],
300                                         makeArrayRef(ElementTypes).slice(1),
301                                         cast<FunctionType>(Ty)->isVarArg());
302     case Type::StructTyID:
303       // Note that this is only reached for anonymous structs.
304       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
305                                       cast<StructType>(Ty)->isPacked());
306     }
307   }
308
309   // Otherwise, this is an unmapped named struct.  If the struct can be directly
310   // mapped over, just use it as-is.  This happens in a case when the linked-in
311   // module has something like:
312   //   %T = type {%T*, i32}
313   //   @GV = global %T* null
314   // where T does not exist at all in the destination module.
315   //
316   // The other case we watch for is when the type is not in the destination
317   // module, but that it has to be rebuilt because it refers to something that
318   // is already mapped.  For example, if the destination module has:
319   //  %A = type { i32 }
320   // and the source module has something like
321   //  %A' = type { i32 }
322   //  %B = type { %A'* }
323   //  @GV = global %B* null
324   // then we want to create a new type: "%B = type { %A*}" and have it take the
325   // pristine "%B" name from the source module.
326   //
327   // To determine which case this is, we have to recursively walk the type graph
328   // speculating that we'll be able to reuse it unmodified.  Only if this is
329   // safe would we map the entire thing over.  Because this is an optimization,
330   // and is not required for the prettiness of the linked module, we just skip
331   // it and always rebuild a type here.
332   StructType *STy = cast<StructType>(Ty);
333   
334   // If the type is opaque, we can just use it directly.
335   if (STy->isOpaque())
336     return *Entry = STy;
337   
338   // Otherwise we create a new type and resolve its body later.  This will be
339   // resolved by the top level of get().
340   SrcDefinitionsToResolve.push_back(STy);
341   StructType *DTy = StructType::create(STy->getContext());
342   DstResolvedOpaqueTypes.insert(DTy);
343   return *Entry = DTy;
344 }
345
346 //===----------------------------------------------------------------------===//
347 // ModuleLinker implementation.
348 //===----------------------------------------------------------------------===//
349
350 namespace {
351   /// ModuleLinker - This is an implementation class for the LinkModules
352   /// function, which is the entrypoint for this file.
353   class ModuleLinker {
354     Module *DstM, *SrcM;
355     
356     TypeMapTy TypeMap; 
357
358     /// ValueMap - Mapping of values from what they used to be in Src, to what
359     /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
360     /// some overhead due to the use of Value handles which the Linker doesn't
361     /// actually need, but this allows us to reuse the ValueMapper code.
362     ValueToValueMapTy ValueMap;
363     
364     struct AppendingVarInfo {
365       GlobalVariable *NewGV;  // New aggregate global in dest module.
366       Constant *DstInit;      // Old initializer from dest module.
367       Constant *SrcInit;      // Old initializer from src module.
368     };
369     
370     std::vector<AppendingVarInfo> AppendingVars;
371     
372     unsigned Mode; // Mode to treat source module.
373     
374     // Set of items not to link in from source.
375     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
376     
377     // Vector of functions to lazily link in.
378     std::vector<Function*> LazilyLinkFunctions;
379     
380   public:
381     std::string ErrorMsg;
382     
383     ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
384       : DstM(dstM), SrcM(srcM), Mode(mode) { }
385     
386     bool run();
387     
388   private:
389     /// emitError - Helper method for setting a message and returning an error
390     /// code.
391     bool emitError(const Twine &Message) {
392       ErrorMsg = Message.str();
393       return true;
394     }
395     
396     /// getLinkageResult - This analyzes the two global values and determines
397     /// what the result will look like in the destination module.
398     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
399                           GlobalValue::LinkageTypes &LT,
400                           GlobalValue::VisibilityTypes &Vis,
401                           bool &LinkFromSrc);
402
403     /// getLinkedToGlobal - Given a global in the source module, return the
404     /// global in the destination module that is being linked to, if any.
405     GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
406       // If the source has no name it can't link.  If it has local linkage,
407       // there is no name match-up going on.
408       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
409         return 0;
410       
411       // Otherwise see if we have a match in the destination module's symtab.
412       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
413       if (DGV == 0) return 0;
414         
415       // If we found a global with the same name in the dest module, but it has
416       // internal linkage, we are really not doing any linkage here.
417       if (DGV->hasLocalLinkage())
418         return 0;
419
420       // Otherwise, we do in fact link to the destination global.
421       return DGV;
422     }
423     
424     void computeTypeMapping();
425     
426     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
427     bool linkGlobalProto(GlobalVariable *SrcGV);
428     bool linkFunctionProto(Function *SrcF);
429     bool linkAliasProto(GlobalAlias *SrcA);
430     bool linkModuleFlagsMetadata();
431     
432     void linkAppendingVarInit(const AppendingVarInfo &AVI);
433     void linkGlobalInits();
434     void linkFunctionBody(Function *Dst, Function *Src);
435     void linkAliasBodies();
436     void linkNamedMDNodes();
437   };
438 }
439
440 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
441 /// in the symbol table.  This is good for all clients except for us.  Go
442 /// through the trouble to force this back.
443 static void forceRenaming(GlobalValue *GV, StringRef Name) {
444   // If the global doesn't force its name or if it already has the right name,
445   // there is nothing for us to do.
446   if (GV->hasLocalLinkage() || GV->getName() == Name)
447     return;
448
449   Module *M = GV->getParent();
450
451   // If there is a conflict, rename the conflict.
452   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
453     GV->takeName(ConflictGV);
454     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
455     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
456   } else {
457     GV->setName(Name);              // Force the name back
458   }
459 }
460
461 /// copyGVAttributes - copy additional attributes (those not needed to construct
462 /// a GlobalValue) from the SrcGV to the DestGV.
463 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
464   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
465   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
466   DestGV->copyAttributesFrom(SrcGV);
467   DestGV->setAlignment(Alignment);
468   
469   forceRenaming(DestGV, SrcGV->getName());
470 }
471
472 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
473                                GlobalValue::VisibilityTypes b) {
474   if (a == GlobalValue::HiddenVisibility)
475     return false;
476   if (b == GlobalValue::HiddenVisibility)
477     return true;
478   if (a == GlobalValue::ProtectedVisibility)
479     return false;
480   if (b == GlobalValue::ProtectedVisibility)
481     return true;
482   return false;
483 }
484
485 /// getLinkageResult - This analyzes the two global values and determines what
486 /// the result will look like in the destination module.  In particular, it
487 /// computes the resultant linkage type and visibility, computes whether the
488 /// global in the source should be copied over to the destination (replacing
489 /// the existing one), and computes whether this linkage is an error or not.
490 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
491                                     GlobalValue::LinkageTypes &LT,
492                                     GlobalValue::VisibilityTypes &Vis,
493                                     bool &LinkFromSrc) {
494   assert(Dest && "Must have two globals being queried");
495   assert(!Src->hasLocalLinkage() &&
496          "If Src has internal linkage, Dest shouldn't be set!");
497   
498   bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
499   bool DestIsDeclaration = Dest->isDeclaration();
500   
501   if (SrcIsDeclaration) {
502     // If Src is external or if both Src & Dest are external..  Just link the
503     // external globals, we aren't adding anything.
504     if (Src->hasDLLImportLinkage()) {
505       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
506       if (DestIsDeclaration) {
507         LinkFromSrc = true;
508         LT = Src->getLinkage();
509       }
510     } else if (Dest->hasExternalWeakLinkage()) {
511       // If the Dest is weak, use the source linkage.
512       LinkFromSrc = true;
513       LT = Src->getLinkage();
514     } else {
515       LinkFromSrc = false;
516       LT = Dest->getLinkage();
517     }
518   } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
519     // If Dest is external but Src is not:
520     LinkFromSrc = true;
521     LT = Src->getLinkage();
522   } else if (Src->isWeakForLinker()) {
523     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
524     // or DLL* linkage.
525     if (Dest->hasExternalWeakLinkage() ||
526         Dest->hasAvailableExternallyLinkage() ||
527         (Dest->hasLinkOnceLinkage() &&
528          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
529       LinkFromSrc = true;
530       LT = Src->getLinkage();
531     } else {
532       LinkFromSrc = false;
533       LT = Dest->getLinkage();
534     }
535   } else if (Dest->isWeakForLinker()) {
536     // At this point we know that Src has External* or DLL* linkage.
537     if (Src->hasExternalWeakLinkage()) {
538       LinkFromSrc = false;
539       LT = Dest->getLinkage();
540     } else {
541       LinkFromSrc = true;
542       LT = GlobalValue::ExternalLinkage;
543     }
544   } else {
545     assert((Dest->hasExternalLinkage()  || Dest->hasDLLImportLinkage() ||
546             Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
547            (Src->hasExternalLinkage()   || Src->hasDLLImportLinkage() ||
548             Src->hasDLLExportLinkage()  || Src->hasExternalWeakLinkage()) &&
549            "Unexpected linkage type!");
550     return emitError("Linking globals named '" + Src->getName() +
551                  "': symbol multiply defined!");
552   }
553
554   // Compute the visibility. We follow the rules in the System V Application
555   // Binary Interface.
556   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
557     Dest->getVisibility() : Src->getVisibility();
558   return false;
559 }
560
561 /// computeTypeMapping - Loop over all of the linked values to compute type
562 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
563 /// we have two struct types 'Foo' but one got renamed when the module was
564 /// loaded into the same LLVMContext.
565 void ModuleLinker::computeTypeMapping() {
566   // Incorporate globals.
567   for (Module::global_iterator I = SrcM->global_begin(),
568        E = SrcM->global_end(); I != E; ++I) {
569     GlobalValue *DGV = getLinkedToGlobal(I);
570     if (DGV == 0) continue;
571     
572     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
573       TypeMap.addTypeMapping(DGV->getType(), I->getType());
574       continue;      
575     }
576     
577     // Unify the element type of appending arrays.
578     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
579     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
580     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
581   }
582   
583   // Incorporate functions.
584   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
585     if (GlobalValue *DGV = getLinkedToGlobal(I))
586       TypeMap.addTypeMapping(DGV->getType(), I->getType());
587   }
588
589   // Incorporate types by name, scanning all the types in the source module.
590   // At this point, the destination module may have a type "%foo = { i32 }" for
591   // example.  When the source module got loaded into the same LLVMContext, if
592   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
593   TypeFinder SrcStructTypes;
594   SrcStructTypes.run(*SrcM, true);
595   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
596                                                  SrcStructTypes.end());
597
598   TypeFinder DstStructTypes;
599   DstStructTypes.run(*DstM, true);
600   SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
601                                                  DstStructTypes.end());
602
603   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
604     StructType *ST = SrcStructTypes[i];
605     if (!ST->hasName()) continue;
606     
607     // Check to see if there is a dot in the name followed by a digit.
608     size_t DotPos = ST->getName().rfind('.');
609     if (DotPos == 0 || DotPos == StringRef::npos ||
610         ST->getName().back() == '.' ||
611         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
612       continue;
613     
614     // Check to see if the destination module has a struct with the prefix name.
615     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
616       // Don't use it if this actually came from the source module. They're in
617       // the same LLVMContext after all. Also don't use it unless the type is
618       // actually used in the destination module. This can happen in situations
619       // like this:
620       //
621       //      Module A                         Module B
622       //      --------                         --------
623       //   %Z = type { %A }                %B = type { %C.1 }
624       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
625       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
626       //   %C = type { i8* }               %B.3 = type { %C.1 }
627       //
628       // When we link Module B with Module A, the '%B' in Module B is
629       // used. However, that would then use '%C.1'. But when we process '%C.1',
630       // we prefer to take the '%C' version. So we are then left with both
631       // '%C.1' and '%C' being used for the same types. This leads to some
632       // variables using one type and some using the other.
633       if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
634         TypeMap.addTypeMapping(DST, ST);
635   }
636
637   // Don't bother incorporating aliases, they aren't generally typed well.
638   
639   // Now that we have discovered all of the type equivalences, get a body for
640   // any 'opaque' types in the dest module that are now resolved. 
641   TypeMap.linkDefinedTypeBodies();
642 }
643
644 /// linkAppendingVarProto - If there were any appending global variables, link
645 /// them together now.  Return true on error.
646 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
647                                          GlobalVariable *SrcGV) {
648  
649   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
650     return emitError("Linking globals named '" + SrcGV->getName() +
651            "': can only link appending global with another appending global!");
652   
653   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
654   ArrayType *SrcTy =
655     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
656   Type *EltTy = DstTy->getElementType();
657   
658   // Check to see that they two arrays agree on type.
659   if (EltTy != SrcTy->getElementType())
660     return emitError("Appending variables with different element types!");
661   if (DstGV->isConstant() != SrcGV->isConstant())
662     return emitError("Appending variables linked with different const'ness!");
663   
664   if (DstGV->getAlignment() != SrcGV->getAlignment())
665     return emitError(
666              "Appending variables with different alignment need to be linked!");
667   
668   if (DstGV->getVisibility() != SrcGV->getVisibility())
669     return emitError(
670             "Appending variables with different visibility need to be linked!");
671   
672   if (DstGV->getSection() != SrcGV->getSection())
673     return emitError(
674           "Appending variables with different section name need to be linked!");
675   
676   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
677   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
678   
679   // Create the new global variable.
680   GlobalVariable *NG =
681     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
682                        DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
683                        DstGV->getThreadLocalMode(),
684                        DstGV->getType()->getAddressSpace());
685   
686   // Propagate alignment, visibility and section info.
687   copyGVAttributes(NG, DstGV);
688   
689   AppendingVarInfo AVI;
690   AVI.NewGV = NG;
691   AVI.DstInit = DstGV->getInitializer();
692   AVI.SrcInit = SrcGV->getInitializer();
693   AppendingVars.push_back(AVI);
694
695   // Replace any uses of the two global variables with uses of the new
696   // global.
697   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
698
699   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
700   DstGV->eraseFromParent();
701   
702   // Track the source variable so we don't try to link it.
703   DoNotLinkFromSource.insert(SrcGV);
704   
705   return false;
706 }
707
708 /// linkGlobalProto - Loop through the global variables in the src module and
709 /// merge them into the dest module.
710 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
711   GlobalValue *DGV = getLinkedToGlobal(SGV);
712   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
713
714   if (DGV) {
715     // Concatenation of appending linkage variables is magic and handled later.
716     if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
717       return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
718     
719     // Determine whether linkage of these two globals follows the source
720     // module's definition or the destination module's definition.
721     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
722     GlobalValue::VisibilityTypes NV;
723     bool LinkFromSrc = false;
724     if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
725       return true;
726     NewVisibility = NV;
727
728     // If we're not linking from the source, then keep the definition that we
729     // have.
730     if (!LinkFromSrc) {
731       // Special case for const propagation.
732       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
733         if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
734           DGVar->setConstant(true);
735       
736       // Set calculated linkage and visibility.
737       DGV->setLinkage(NewLinkage);
738       DGV->setVisibility(*NewVisibility);
739
740       // Make sure to remember this mapping.
741       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
742       
743       // Track the source global so that we don't attempt to copy it over when 
744       // processing global initializers.
745       DoNotLinkFromSource.insert(SGV);
746       
747       return false;
748     }
749   }
750   
751   // No linking to be performed or linking from the source: simply create an
752   // identical version of the symbol over in the dest module... the
753   // initializer will be filled in later by LinkGlobalInits.
754   GlobalVariable *NewDGV =
755     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
756                        SGV->isConstant(), SGV->getLinkage(), /*init*/0,
757                        SGV->getName(), /*insertbefore*/0,
758                        SGV->getThreadLocalMode(),
759                        SGV->getType()->getAddressSpace());
760   // Propagate alignment, visibility and section info.
761   copyGVAttributes(NewDGV, SGV);
762   if (NewVisibility)
763     NewDGV->setVisibility(*NewVisibility);
764
765   if (DGV) {
766     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
767     DGV->eraseFromParent();
768   }
769   
770   // Make sure to remember this mapping.
771   ValueMap[SGV] = NewDGV;
772   return false;
773 }
774
775 /// linkFunctionProto - Link the function in the source module into the
776 /// destination module if needed, setting up mapping information.
777 bool ModuleLinker::linkFunctionProto(Function *SF) {
778   GlobalValue *DGV = getLinkedToGlobal(SF);
779   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
780
781   if (DGV) {
782     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
783     bool LinkFromSrc = false;
784     GlobalValue::VisibilityTypes NV;
785     if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
786       return true;
787     NewVisibility = NV;
788
789     if (!LinkFromSrc) {
790       // Set calculated linkage
791       DGV->setLinkage(NewLinkage);
792       DGV->setVisibility(*NewVisibility);
793
794       // Make sure to remember this mapping.
795       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
796       
797       // Track the function from the source module so we don't attempt to remap 
798       // it.
799       DoNotLinkFromSource.insert(SF);
800       
801       return false;
802     }
803   }
804   
805   // If there is no linkage to be performed or we are linking from the source,
806   // bring SF over.
807   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
808                                      SF->getLinkage(), SF->getName(), DstM);
809   copyGVAttributes(NewDF, SF);
810   if (NewVisibility)
811     NewDF->setVisibility(*NewVisibility);
812
813   if (DGV) {
814     // Any uses of DF need to change to NewDF, with cast.
815     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
816     DGV->eraseFromParent();
817   } else {
818     // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
819     if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
820         SF->hasAvailableExternallyLinkage()) {
821       DoNotLinkFromSource.insert(SF);
822       LazilyLinkFunctions.push_back(SF);
823     }
824   }
825   
826   ValueMap[SF] = NewDF;
827   return false;
828 }
829
830 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
831 /// source module.
832 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
833   GlobalValue *DGV = getLinkedToGlobal(SGA);
834   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
835
836   if (DGV) {
837     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
838     GlobalValue::VisibilityTypes NV;
839     bool LinkFromSrc = false;
840     if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
841       return true;
842     NewVisibility = NV;
843
844     if (!LinkFromSrc) {
845       // Set calculated linkage.
846       DGV->setLinkage(NewLinkage);
847       DGV->setVisibility(*NewVisibility);
848
849       // Make sure to remember this mapping.
850       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
851       
852       // Track the alias from the source module so we don't attempt to remap it.
853       DoNotLinkFromSource.insert(SGA);
854       
855       return false;
856     }
857   }
858   
859   // If there is no linkage to be performed or we're linking from the source,
860   // bring over SGA.
861   GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
862                                        SGA->getLinkage(), SGA->getName(),
863                                        /*aliasee*/0, DstM);
864   copyGVAttributes(NewDA, SGA);
865   if (NewVisibility)
866     NewDA->setVisibility(*NewVisibility);
867
868   if (DGV) {
869     // Any uses of DGV need to change to NewDA, with cast.
870     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
871     DGV->eraseFromParent();
872   }
873   
874   ValueMap[SGA] = NewDA;
875   return false;
876 }
877
878 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
879   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
880
881   for (unsigned i = 0; i != NumElements; ++i)
882     Dest.push_back(C->getAggregateElement(i));
883 }
884                              
885 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
886   // Merge the initializer.
887   SmallVector<Constant*, 16> Elements;
888   getArrayElements(AVI.DstInit, Elements);
889   
890   Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
891   getArrayElements(SrcInit, Elements);
892   
893   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
894   AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
895 }
896
897 /// linkGlobalInits - Update the initializers in the Dest module now that all
898 /// globals that may be referenced are in Dest.
899 void ModuleLinker::linkGlobalInits() {
900   // Loop over all of the globals in the src module, mapping them over as we go
901   for (Module::const_global_iterator I = SrcM->global_begin(),
902        E = SrcM->global_end(); I != E; ++I) {
903     
904     // Only process initialized GV's or ones not already in dest.
905     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;          
906     
907     // Grab destination global variable.
908     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
909     // Figure out what the initializer looks like in the dest module.
910     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
911                                  RF_None, &TypeMap));
912   }
913 }
914
915 /// linkFunctionBody - Copy the source function over into the dest function and
916 /// fix up references to values.  At this point we know that Dest is an external
917 /// function, and that Src is not.
918 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
919   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
920
921   // Go through and convert function arguments over, remembering the mapping.
922   Function::arg_iterator DI = Dst->arg_begin();
923   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
924        I != E; ++I, ++DI) {
925     DI->setName(I->getName());  // Copy the name over.
926
927     // Add a mapping to our mapping.
928     ValueMap[I] = DI;
929   }
930
931   if (Mode == Linker::DestroySource) {
932     // Splice the body of the source function into the dest function.
933     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
934     
935     // At this point, all of the instructions and values of the function are now
936     // copied over.  The only problem is that they are still referencing values in
937     // the Source function as operands.  Loop through all of the operands of the
938     // functions and patch them up to point to the local versions.
939     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
940       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
941         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
942     
943   } else {
944     // Clone the body of the function into the dest function.
945     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
946     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
947   }
948   
949   // There is no need to map the arguments anymore.
950   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
951        I != E; ++I)
952     ValueMap.erase(I);
953   
954 }
955
956 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
957 void ModuleLinker::linkAliasBodies() {
958   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
959        I != E; ++I) {
960     if (DoNotLinkFromSource.count(I))
961       continue;
962     if (Constant *Aliasee = I->getAliasee()) {
963       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
964       DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
965     }
966   }
967 }
968
969 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
970 /// module.
971 void ModuleLinker::linkNamedMDNodes() {
972   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
973   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
974        E = SrcM->named_metadata_end(); I != E; ++I) {
975     // Don't link module flags here. Do them separately.
976     if (&*I == SrcModFlags) continue;
977     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
978     // Add Src elements into Dest node.
979     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
980       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
981                                    RF_None, &TypeMap));
982   }
983 }
984
985 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
986 /// module.
987 bool ModuleLinker::linkModuleFlagsMetadata() {
988   // If the source module has no module flags, we are done.
989   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
990   if (!SrcModFlags) return false;
991
992   // If the destination module doesn't have module flags yet, then just copy
993   // over the source module's flags.
994   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
995   if (DstModFlags->getNumOperands() == 0) {
996     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
997       DstModFlags->addOperand(SrcModFlags->getOperand(I));
998
999     return false;
1000   }
1001
1002   // First build a map of the existing module flags and requirements.
1003   DenseMap<MDString*, MDNode*> Flags;
1004   SmallSetVector<MDNode*, 16> Requirements;
1005   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1006     MDNode *Op = DstModFlags->getOperand(I);
1007     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1008     MDString *ID = cast<MDString>(Op->getOperand(1));
1009
1010     if (Behavior->getZExtValue() == Module::Require) {
1011       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1012     } else {
1013       Flags[ID] = Op;
1014     }
1015   }
1016
1017   // Merge in the flags from the source module, and also collect its set of
1018   // requirements.
1019   bool HasErr = false;
1020   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1021     MDNode *SrcOp = SrcModFlags->getOperand(I);
1022     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1023     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1024     MDNode *DstOp = Flags.lookup(ID);
1025     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1026
1027     // If this is a requirement, add it and continue.
1028     if (SrcBehaviorValue == Module::Require) {
1029       // If the destination module does not already have this requirement, add
1030       // it.
1031       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1032         DstModFlags->addOperand(SrcOp);
1033       }
1034       continue;
1035     }
1036
1037     // If there is no existing flag with this ID, just add it.
1038     if (!DstOp) {
1039       Flags[ID] = SrcOp;
1040       DstModFlags->addOperand(SrcOp);
1041       continue;
1042     }
1043
1044     // Otherwise, perform a merge.
1045     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1046     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1047
1048     // If either flag has override behavior, handle it first.
1049     if (DstBehaviorValue == Module::Override) {
1050       // Diagnose inconsistent flags which both have override behavior.
1051       if (SrcBehaviorValue == Module::Override &&
1052           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1053         HasErr |= emitError("linking module flags '" + ID->getString() +
1054                             "': IDs have conflicting override values");
1055       }
1056       continue;
1057     } else if (SrcBehaviorValue == Module::Override) {
1058       // Update the destination flag to that of the source.
1059       DstOp->replaceOperandWith(0, SrcBehavior);
1060       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1061       continue;
1062     }
1063
1064     // Diagnose inconsistent merge behavior types.
1065     if (SrcBehaviorValue != DstBehaviorValue) {
1066       HasErr |= emitError("linking module flags '" + ID->getString() +
1067                           "': IDs have conflicting behaviors");
1068       continue;
1069     }
1070
1071     // Perform the merge for standard behavior types.
1072     switch (SrcBehaviorValue) {
1073     case Module::Require:
1074     case Module::Override: assert(0 && "not possible"); break;
1075     case Module::Error: {
1076       // Emit an error if the values differ.
1077       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1078         HasErr |= emitError("linking module flags '" + ID->getString() +
1079                             "': IDs have conflicting values");
1080       }
1081       continue;
1082     }
1083     case Module::Warning: {
1084       // Emit a warning if the values differ.
1085       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1086         errs() << "WARNING: linking module flags '" << ID->getString()
1087                << "': IDs have conflicting values";
1088       }
1089       continue;
1090     }
1091     case Module::Append: {
1092       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1093       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1094       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1095       Value **VP, **Values = VP = new Value*[NumOps];
1096       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1097         *VP = DstValue->getOperand(i);
1098       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1099         *VP = SrcValue->getOperand(i);
1100       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1101                                                ArrayRef<Value*>(Values,
1102                                                                 NumOps)));
1103       delete[] Values;
1104       break;
1105     }
1106     case Module::AppendUnique: {
1107       SmallSetVector<Value*, 16> Elts;
1108       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1109       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1110       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1111         Elts.insert(DstValue->getOperand(i));
1112       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1113         Elts.insert(SrcValue->getOperand(i));
1114       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1115                                                ArrayRef<Value*>(Elts.begin(),
1116                                                                 Elts.end())));
1117       break;
1118     }
1119     }
1120   }
1121
1122   // Check all of the requirements.
1123   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1124     MDNode *Requirement = Requirements[I];
1125     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1126     Value *ReqValue = Requirement->getOperand(1);
1127
1128     MDNode *Op = Flags[Flag];
1129     if (!Op || Op->getOperand(2) != ReqValue) {
1130       HasErr |= emitError("linking module flags '" + Flag->getString() +
1131                           "': does not have the required value");
1132       continue;
1133     }
1134   }
1135
1136   return HasErr;
1137 }
1138   
1139 bool ModuleLinker::run() {
1140   assert(DstM && "Null destination module");
1141   assert(SrcM && "Null source module");
1142
1143   // Inherit the target data from the source module if the destination module
1144   // doesn't have one already.
1145   if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1146     DstM->setDataLayout(SrcM->getDataLayout());
1147
1148   // Copy the target triple from the source to dest if the dest's is empty.
1149   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1150     DstM->setTargetTriple(SrcM->getTargetTriple());
1151
1152   if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1153       SrcM->getDataLayout() != DstM->getDataLayout())
1154     errs() << "WARNING: Linking two modules of different data layouts!\n";
1155   if (!SrcM->getTargetTriple().empty() &&
1156       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1157     errs() << "WARNING: Linking two modules of different target triples: ";
1158     if (!SrcM->getModuleIdentifier().empty())
1159       errs() << SrcM->getModuleIdentifier() << ": ";
1160     errs() << "'" << SrcM->getTargetTriple() << "' and '" 
1161            << DstM->getTargetTriple() << "'\n";
1162   }
1163
1164   // Append the module inline asm string.
1165   if (!SrcM->getModuleInlineAsm().empty()) {
1166     if (DstM->getModuleInlineAsm().empty())
1167       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1168     else
1169       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1170                                SrcM->getModuleInlineAsm());
1171   }
1172
1173   // Loop over all of the linked values to compute type mappings.
1174   computeTypeMapping();
1175
1176   // Insert all of the globals in src into the DstM module... without linking
1177   // initializers (which could refer to functions not yet mapped over).
1178   for (Module::global_iterator I = SrcM->global_begin(),
1179        E = SrcM->global_end(); I != E; ++I)
1180     if (linkGlobalProto(I))
1181       return true;
1182
1183   // Link the functions together between the two modules, without doing function
1184   // bodies... this just adds external function prototypes to the DstM
1185   // function...  We do this so that when we begin processing function bodies,
1186   // all of the global values that may be referenced are available in our
1187   // ValueMap.
1188   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1189     if (linkFunctionProto(I))
1190       return true;
1191
1192   // If there were any aliases, link them now.
1193   for (Module::alias_iterator I = SrcM->alias_begin(),
1194        E = SrcM->alias_end(); I != E; ++I)
1195     if (linkAliasProto(I))
1196       return true;
1197
1198   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1199     linkAppendingVarInit(AppendingVars[i]);
1200   
1201   // Update the initializers in the DstM module now that all globals that may
1202   // be referenced are in DstM.
1203   linkGlobalInits();
1204
1205   // Link in the function bodies that are defined in the source module into
1206   // DstM.
1207   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1208     // Skip if not linking from source.
1209     if (DoNotLinkFromSource.count(SF)) continue;
1210     
1211     // Skip if no body (function is external) or materialize.
1212     if (SF->isDeclaration()) {
1213       if (!SF->isMaterializable())
1214         continue;
1215       if (SF->Materialize(&ErrorMsg))
1216         return true;
1217     }
1218     
1219     linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1220     SF->Dematerialize();
1221   }
1222
1223   // Resolve all uses of aliases with aliasees.
1224   linkAliasBodies();
1225
1226   // Remap all of the named MDNodes in Src into the DstM module. We do this
1227   // after linking GlobalValues so that MDNodes that reference GlobalValues
1228   // are properly remapped.
1229   linkNamedMDNodes();
1230
1231   // Merge the module flags into the DstM module.
1232   if (linkModuleFlagsMetadata())
1233     return true;
1234
1235   // Process vector of lazily linked in functions.
1236   bool LinkedInAnyFunctions;
1237   do {
1238     LinkedInAnyFunctions = false;
1239     
1240     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1241         E = LazilyLinkFunctions.end(); I != E; ++I) {
1242       if (!*I)
1243         continue;
1244       
1245       Function *SF = *I;
1246       Function *DF = cast<Function>(ValueMap[SF]);
1247       
1248       if (!DF->use_empty()) {
1249         
1250         // Materialize if necessary.
1251         if (SF->isDeclaration()) {
1252           if (!SF->isMaterializable())
1253             continue;
1254           if (SF->Materialize(&ErrorMsg))
1255             return true;
1256         }
1257         
1258         // Link in function body.
1259         linkFunctionBody(DF, SF);
1260         SF->Dematerialize();
1261
1262         // "Remove" from vector by setting the element to 0.
1263         *I = 0;
1264         
1265         // Set flag to indicate we may have more functions to lazily link in
1266         // since we linked in a function.
1267         LinkedInAnyFunctions = true;
1268       }
1269     }
1270   } while (LinkedInAnyFunctions);
1271   
1272   // Remove any prototypes of functions that were not actually linked in.
1273   for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1274       E = LazilyLinkFunctions.end(); I != E; ++I) {
1275     if (!*I)
1276       continue;
1277     
1278     Function *SF = *I;
1279     Function *DF = cast<Function>(ValueMap[SF]);
1280     if (DF->use_empty())
1281       DF->eraseFromParent();
1282   }
1283   
1284   // Now that all of the types from the source are used, resolve any structs
1285   // copied over to the dest that didn't exist there.
1286   TypeMap.linkDefinedTypeBodies();
1287   
1288   return false;
1289 }
1290
1291 //===----------------------------------------------------------------------===//
1292 // LinkModules entrypoint.
1293 //===----------------------------------------------------------------------===//
1294
1295 /// LinkModules - This function links two modules together, with the resulting
1296 /// Dest module modified to be the composite of the two input modules.  If an
1297 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1298 /// the problem.  Upon failure, the Dest module could be in a modified state,
1299 /// and shouldn't be relied on to be consistent.
1300 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode, 
1301                          std::string *ErrorMsg) {
1302   ModuleLinker TheLinker(Dest, Src, Mode);
1303   if (TheLinker.run()) {
1304     if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
1305     return true;
1306   }
1307
1308   return false;
1309 }
1310
1311 //===----------------------------------------------------------------------===//
1312 // C API.
1313 //===----------------------------------------------------------------------===//
1314
1315 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1316                          LLVMLinkerMode Mode, char **OutMessages) {
1317   std::string Messages;
1318   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1319                                         Mode, OutMessages? &Messages : 0);
1320   if (OutMessages)
1321     *OutMessages = strdup(Messages.c_str());
1322   return Result;
1323 }