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