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