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