Fix
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM module linker.
11 //
12 // Specifically, this:
13 //  * Merges global variables between the two modules
14 //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15 //  * Merges functions between two modules
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Linker.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/Support/Streams.h"
28 #include "llvm/System/Path.h"
29 #include <sstream>
30 using namespace llvm;
31
32 // Error - Simple wrapper function to conditionally assign to E and return true.
33 // This just makes error return conditions a little bit simpler...
34 static inline bool Error(std::string *E, const std::string &Message) {
35   if (E) *E = Message;
36   return true;
37 }
38
39 // ToStr - Simple wrapper function to convert a type to a string.
40 static std::string ToStr(const Type *Ty, const Module *M) {
41   std::ostringstream OS;
42   WriteTypeSymbolic(OS, Ty, M);
43   return OS.str();
44 }
45
46 //
47 // Function: ResolveTypes()
48 //
49 // Description:
50 //  Attempt to link the two specified types together.
51 //
52 // Inputs:
53 //  DestTy - The type to which we wish to resolve.
54 //  SrcTy  - The original type which we want to resolve.
55 //  Name   - The name of the type.
56 //
57 // Outputs:
58 //  DestST - The symbol table in which the new type should be placed.
59 //
60 // Return value:
61 //  true  - There is an error and the types cannot yet be linked.
62 //  false - No errors.
63 //
64 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
65                          TypeSymbolTable *DestST, const std::string &Name) {
66   if (DestTy == SrcTy) return false;       // If already equal, noop
67
68   // Does the type already exist in the module?
69   if (DestTy && !isa<OpaqueType>(DestTy)) {  // Yup, the type already exists...
70     if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
71       const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
72     } else {
73       return true;  // Cannot link types... neither is opaque and not-equal
74     }
75   } else {                       // Type not in dest module.  Add it now.
76     if (DestTy)                  // Type _is_ in module, just opaque...
77       const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
78                            ->refineAbstractTypeTo(SrcTy);
79     else if (!Name.empty())
80       DestST->insert(Name, const_cast<Type*>(SrcTy));
81   }
82   return false;
83 }
84
85 static const FunctionType *getFT(const PATypeHolder &TH) {
86   return cast<FunctionType>(TH.get());
87 }
88 static const StructType *getST(const PATypeHolder &TH) {
89   return cast<StructType>(TH.get());
90 }
91
92 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
93 // recurses down into derived types, merging the used types if the parent types
94 // are compatible.
95 static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
96                                    const PATypeHolder &SrcTy,
97                                    TypeSymbolTable *DestST, 
98                                    const std::string &Name,
99                 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
100   const Type *SrcTyT = SrcTy.get();
101   const Type *DestTyT = DestTy.get();
102   if (DestTyT == SrcTyT) return false;       // If already equal, noop
103
104   // If we found our opaque type, resolve it now!
105   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
106     return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
107
108   // Two types cannot be resolved together if they are of different primitive
109   // type.  For example, we cannot resolve an int to a float.
110   if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
111
112   // Otherwise, resolve the used type used by this derived type...
113   switch (DestTyT->getTypeID()) {
114   case Type::IntegerTyID: {
115     if (cast<IntegerType>(DestTyT)->getBitWidth() !=
116         cast<IntegerType>(SrcTyT)->getBitWidth())
117       return true;
118     return false;
119   }
120   case Type::FunctionTyID: {
121     if (cast<FunctionType>(DestTyT)->isVarArg() !=
122         cast<FunctionType>(SrcTyT)->isVarArg() ||
123         cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
124         cast<FunctionType>(SrcTyT)->getNumContainedTypes())
125       return true;
126     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
127       if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
128                                  getFT(SrcTy)->getContainedType(i), DestST, "",
129                                  Pointers))
130         return true;
131     return false;
132   }
133   case Type::StructTyID: {
134     if (getST(DestTy)->getNumContainedTypes() !=
135         getST(SrcTy)->getNumContainedTypes()) return 1;
136     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
137       if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
138                                  getST(SrcTy)->getContainedType(i), DestST, "",
139                                  Pointers))
140         return true;
141     return false;
142   }
143   case Type::ArrayTyID: {
144     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
145     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
146     if (DAT->getNumElements() != SAT->getNumElements()) return true;
147     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
148                                   DestST, "", Pointers);
149   }
150   case Type::PointerTyID: {
151     // If this is a pointer type, check to see if we have already seen it.  If
152     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
153     // an associative container for this search, because the type pointers (keys
154     // in the container) change whenever types get resolved...
155     for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
156       if (Pointers[i].first == DestTy)
157         return Pointers[i].second != SrcTy;
158
159     // Otherwise, add the current pointers to the vector to stop recursion on
160     // this pair.
161     Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
162     bool Result =
163       RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
164                              cast<PointerType>(SrcTy.get())->getElementType(),
165                              DestST, "", Pointers);
166     Pointers.pop_back();
167     return Result;
168   }
169   default: assert(0 && "Unexpected type!"); return true;
170   }
171 }
172
173 static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
174                                   const PATypeHolder &SrcTy,
175                                   TypeSymbolTable *DestST, 
176                                   const std::string &Name){
177   std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
178   return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
179 }
180
181
182 // LinkTypes - Go through the symbol table of the Src module and see if any
183 // types are named in the src module that are not named in the Dst module.
184 // Make sure there are no type name conflicts.
185 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
186         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
187   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
188
189   // Look for a type plane for Type's...
190   TypeSymbolTable::const_iterator TI = SrcST->begin();
191   TypeSymbolTable::const_iterator TE = SrcST->end();
192   if (TI == TE) return false;  // No named types, do nothing.
193
194   // Some types cannot be resolved immediately because they depend on other
195   // types being resolved to each other first.  This contains a list of types we
196   // are waiting to recheck.
197   std::vector<std::string> DelayedTypesToResolve;
198
199   for ( ; TI != TE; ++TI ) {
200     const std::string &Name = TI->first;
201     const Type *RHS = TI->second;
202
203     // Check to see if this type name is already in the dest module...
204     Type *Entry = DestST->lookup(Name);
205
206     if (ResolveTypes(Entry, RHS, DestST, Name)) {
207       // They look different, save the types 'till later to resolve.
208       DelayedTypesToResolve.push_back(Name);
209     }
210   }
211
212   // Iteratively resolve types while we can...
213   while (!DelayedTypesToResolve.empty()) {
214     // Loop over all of the types, attempting to resolve them if possible...
215     unsigned OldSize = DelayedTypesToResolve.size();
216
217     // Try direct resolution by name...
218     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
219       const std::string &Name = DelayedTypesToResolve[i];
220       Type *T1 = SrcST->lookup(Name);
221       Type *T2 = DestST->lookup(Name);
222       if (!ResolveTypes(T2, T1, DestST, Name)) {
223         // We are making progress!
224         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
225         --i;
226       }
227     }
228
229     // Did we not eliminate any types?
230     if (DelayedTypesToResolve.size() == OldSize) {
231       // Attempt to resolve subelements of types.  This allows us to merge these
232       // two types: { int* } and { opaque* }
233       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
234         const std::string &Name = DelayedTypesToResolve[i];
235         PATypeHolder T1(SrcST->lookup(Name));
236         PATypeHolder T2(DestST->lookup(Name));
237
238         if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
239           // We are making progress!
240           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
241
242           // Go back to the main loop, perhaps we can resolve directly by name
243           // now...
244           break;
245         }
246       }
247
248       // If we STILL cannot resolve the types, then there is something wrong.
249       if (DelayedTypesToResolve.size() == OldSize) {
250         // Remove the symbol name from the destination.
251         DelayedTypesToResolve.pop_back();
252       }
253     }
254   }
255
256
257   return false;
258 }
259
260 static void PrintMap(const std::map<const Value*, Value*> &M) {
261   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
262        I != E; ++I) {
263     cerr << " Fr: " << (void*)I->first << " ";
264     I->first->dump();
265     cerr << " To: " << (void*)I->second << " ";
266     I->second->dump();
267     cerr << "\n";
268   }
269 }
270
271
272 // RemapOperand - Use ValueMap to convert constants from one module to another.
273 static Value *RemapOperand(const Value *In,
274                            std::map<const Value*, Value*> &ValueMap) {
275   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
276   if (I != ValueMap.end()) 
277     return I->second;
278
279   // Check to see if it's a constant that we are interested in transforming.
280   Value *Result = 0;
281   if (const Constant *CPV = dyn_cast<Constant>(In)) {
282     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
283         isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
284       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
285
286     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
287       std::vector<Constant*> Operands(CPA->getNumOperands());
288       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
289         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
290       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
291     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
292       std::vector<Constant*> Operands(CPS->getNumOperands());
293       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
294         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
295       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
296     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
297       Result = const_cast<Constant*>(CPV);
298     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
299       std::vector<Constant*> Operands(CP->getNumOperands());
300       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
301         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
302       Result = ConstantVector::get(Operands);
303     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
304       std::vector<Constant*> Ops;
305       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
306         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
307       Result = CE->getWithOperands(Ops);
308     } else if (isa<GlobalValue>(CPV)) {
309       assert(0 && "Unmapped global?");
310     } else {
311       assert(0 && "Unknown type of derived type constant value!");
312     }
313   } else if (isa<InlineAsm>(In)) {
314     Result = const_cast<Value*>(In);
315   }
316   
317   // Cache the mapping in our local map structure
318   if (Result) {
319     ValueMap.insert(std::make_pair(In, Result));
320     return Result;
321   }
322   
323
324   cerr << "LinkModules ValueMap: \n";
325   PrintMap(ValueMap);
326
327   cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
328   assert(0 && "Couldn't remap value!");
329   return 0;
330 }
331
332 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
333 /// in the symbol table.  This is good for all clients except for us.  Go
334 /// through the trouble to force this back.
335 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
336   assert(GV->getName() != Name && "Can't force rename to self");
337   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
338
339   // If there is a conflict, rename the conflict.
340   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
341     assert(ConflictGV->hasInternalLinkage() &&
342            "Not conflicting with a static global, should link instead!");
343     GV->takeName(ConflictGV);
344     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
345     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
346   } else {
347     GV->setName(Name);              // Force the name back
348   }
349 }
350
351 /// CopyGVAttributes - copy additional attributes (those not needed to construct
352 /// a GlobalValue) from the SrcGV to the DestGV. 
353 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
354   // Propagate alignment, visibility and section info.
355   DestGV->setAlignment(std::max(DestGV->getAlignment(), SrcGV->getAlignment()));
356   DestGV->setSection(SrcGV->getSection());
357   DestGV->setVisibility(SrcGV->getVisibility());
358   if (const Function *SrcF = dyn_cast<Function>(SrcGV)) {
359     Function *DestF = cast<Function>(DestGV);
360     DestF->setCallingConv(SrcF->getCallingConv());
361   }
362 }
363
364 /// GetLinkageResult - This analyzes the two global values and determines what
365 /// the result will look like in the destination module.  In particular, it
366 /// computes the resultant linkage type, computes whether the global in the
367 /// source should be copied over to the destination (replacing the existing
368 /// one), and computes whether this linkage is an error or not.
369 static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
370                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
371                              std::string *Err) {
372   assert((!Dest || !Src->hasInternalLinkage()) &&
373          "If Src has internal linkage, Dest shouldn't be set!");
374   if (!Dest) {
375     // Linking something to nothing.
376     LinkFromSrc = true;
377     LT = Src->getLinkage();
378   } else if (Src->isDeclaration()) {
379     // If Src is external or if both Src & Drc are external..  Just link the
380     // external globals, we aren't adding anything.
381     if (Src->hasDLLImportLinkage()) {
382       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
383       if (Dest->isDeclaration()) {
384         LinkFromSrc = true;
385         LT = Src->getLinkage();
386       }      
387     } else if (Dest->hasExternalWeakLinkage()) {
388       //If the Dest is weak, use the source linkage
389       LinkFromSrc = true;
390       LT = Src->getLinkage();
391     } else {
392       LinkFromSrc = false;
393       LT = Dest->getLinkage();
394     }
395   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
396     // If Dest is external but Src is not:
397     LinkFromSrc = true;
398     LT = Src->getLinkage();
399   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
400     if (Src->getLinkage() != Dest->getLinkage())
401       return Error(Err, "Linking globals named '" + Src->getName() +
402             "': can only link appending global with another appending global!");
403     LinkFromSrc = true; // Special cased.
404     LT = Src->getLinkage();
405   } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
406     // At this point we know that Dest has LinkOnce, External*, Weak, or
407     // DLL* linkage.
408     if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
409         Dest->hasExternalWeakLinkage()) {
410       LinkFromSrc = true;
411       LT = Src->getLinkage();
412     } else {
413       LinkFromSrc = false;
414       LT = Dest->getLinkage();
415     }
416   } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
417     // At this point we know that Src has External* or DLL* linkage.
418     if (Src->hasExternalWeakLinkage()) {
419       LinkFromSrc = false;
420       LT = Dest->getLinkage();
421     } else {
422       LinkFromSrc = true;
423       LT = GlobalValue::ExternalLinkage;
424     }
425   } else {
426     assert((Dest->hasExternalLinkage() ||
427             Dest->hasDLLImportLinkage() ||
428             Dest->hasDLLExportLinkage() ||
429             Dest->hasExternalWeakLinkage()) &&
430            (Src->hasExternalLinkage() ||
431             Src->hasDLLImportLinkage() ||
432             Src->hasDLLExportLinkage() ||
433             Src->hasExternalWeakLinkage()) &&
434            "Unexpected linkage type!");
435     return Error(Err, "Linking globals named '" + Src->getName() +
436                  "': symbol multiply defined!");
437   }
438   return false;
439 }
440
441 // LinkGlobals - Loop through the global variables in the src module and merge
442 // them into the dest module.
443 static bool LinkGlobals(Module *Dest, Module *Src,
444                         std::map<const Value*, Value*> &ValueMap,
445                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
446                         std::string *Err) {
447   // Loop over all of the globals in the src module, mapping them over as we go
448   for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
449        I != E; ++I) {
450     GlobalVariable *SGV = I;
451     GlobalVariable *DGV = 0;
452     // Check to see if may have to link the global.
453     if (SGV->hasName() && !SGV->hasInternalLinkage()) {
454       DGV = Dest->getGlobalVariable(SGV->getName());
455       if (DGV && DGV->getType() != SGV->getType())
456         // If types don't agree due to opaque types, try to resolve them.
457         RecursiveResolveTypes(SGV->getType(), DGV->getType(), 
458                               &Dest->getTypeSymbolTable(), "");
459     }
460
461     if (DGV && DGV->hasInternalLinkage())
462       DGV = 0;
463
464     assert(SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
465            SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage() &&
466            "Global must either be external or have an initializer!");
467
468     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
469     bool LinkFromSrc = false;
470     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
471       return true;
472
473     if (!DGV) {
474       // No linking to be performed, simply create an identical version of the
475       // symbol over in the dest module... the initializer will be filled in
476       // later by LinkGlobalInits...
477       GlobalVariable *NewDGV =
478         new GlobalVariable(SGV->getType()->getElementType(),
479                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
480                            SGV->getName(), Dest, SGV->isThreadLocal());
481       // Propagate alignment, visibility and section info.
482       CopyGVAttributes(NewDGV, SGV);
483
484       // If the LLVM runtime renamed the global, but it is an externally visible
485       // symbol, DGV must be an existing global with internal linkage.  Rename
486       // it.
487       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
488         ForceRenaming(NewDGV, SGV->getName());
489
490       // Make sure to remember this mapping...
491       ValueMap.insert(std::make_pair(SGV, NewDGV));
492       if (SGV->hasAppendingLinkage())
493         // Keep track that this is an appending variable...
494         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
495     } else if (DGV->hasAppendingLinkage()) {
496       // No linking is performed yet.  Just insert a new copy of the global, and
497       // keep track of the fact that it is an appending variable in the
498       // AppendingVars map.  The name is cleared out so that no linkage is
499       // performed.
500       GlobalVariable *NewDGV =
501         new GlobalVariable(SGV->getType()->getElementType(),
502                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
503                            "", Dest, SGV->isThreadLocal());
504
505       // Propagate alignment, section and visibility  info.
506       NewDGV->setAlignment(DGV->getAlignment());
507       CopyGVAttributes(NewDGV, SGV);
508
509       // Make sure to remember this mapping...
510       ValueMap.insert(std::make_pair(SGV, NewDGV));
511
512       // Keep track that this is an appending variable...
513       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
514     } else {
515       // Propagate alignment, section, and visibility info.
516       CopyGVAttributes(DGV, SGV);
517
518       // Otherwise, perform the mapping as instructed by GetLinkageResult.  If
519       // the types don't match, and if we are to link from the source, nuke DGV
520       // and create a new one of the appropriate type.
521       if (SGV->getType() != DGV->getType() && LinkFromSrc) {
522         GlobalVariable *NewDGV =
523           new GlobalVariable(SGV->getType()->getElementType(),
524                              DGV->isConstant(), DGV->getLinkage());
525         NewDGV->setThreadLocal(DGV->isThreadLocal());
526         CopyGVAttributes(NewDGV, DGV);
527         Dest->getGlobalList().insert(DGV, NewDGV);
528         DGV->replaceAllUsesWith(
529             ConstantExpr::getBitCast(NewDGV, DGV->getType()));
530         DGV->eraseFromParent();
531         NewDGV->setName(SGV->getName());
532         DGV = NewDGV;
533       }
534
535       DGV->setLinkage(NewLinkage);
536
537       if (LinkFromSrc) {
538         // Inherit const as appropriate
539         DGV->setConstant(SGV->isConstant());
540         DGV->setInitializer(0);
541       } else {
542         if (SGV->isConstant() && !DGV->isConstant()) {
543           if (DGV->isDeclaration())
544             DGV->setConstant(true);
545         }
546         SGV->setLinkage(GlobalValue::ExternalLinkage);
547         SGV->setInitializer(0);
548       }
549
550       ValueMap.insert(
551         std::make_pair(SGV, ConstantExpr::getBitCast(DGV, SGV->getType())));
552     }
553   }
554   return false;
555 }
556
557
558 // LinkGlobalInits - Update the initializers in the Dest module now that all
559 // globals that may be referenced are in Dest.
560 static bool LinkGlobalInits(Module *Dest, const Module *Src,
561                             std::map<const Value*, Value*> &ValueMap,
562                             std::string *Err) {
563
564   // Loop over all of the globals in the src module, mapping them over as we go
565   for (Module::const_global_iterator I = Src->global_begin(),
566        E = Src->global_end(); I != E; ++I) {
567     const GlobalVariable *SGV = I;
568
569     if (SGV->hasInitializer()) {      // Only process initialized GV's
570       // Figure out what the initializer looks like in the dest module...
571       Constant *SInit =
572         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
573
574       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
575       if (DGV->hasInitializer()) {
576         if (SGV->hasExternalLinkage()) {
577           if (DGV->getInitializer() != SInit)
578             return Error(Err, "Global Variable Collision on '" +
579                          ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
580                          " - Global variables have different initializers");
581         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
582           // Nothing is required, mapped values will take the new global
583           // automatically.
584         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
585           // Nothing is required, mapped values will take the new global
586           // automatically.
587         } else if (DGV->hasAppendingLinkage()) {
588           assert(0 && "Appending linkage unimplemented!");
589         } else {
590           assert(0 && "Unknown linkage!");
591         }
592       } else {
593         // Copy the initializer over now...
594         DGV->setInitializer(SInit);
595       }
596     }
597   }
598   return false;
599 }
600
601 // LinkFunctionProtos - Link the functions together between the two modules,
602 // without doing function bodies... this just adds external function prototypes
603 // to the Dest function...
604 //
605 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
606                                std::map<const Value*, Value*> &ValueMap,
607                                std::string *Err) {
608   // Loop over all of the functions in the src module, mapping them over
609   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
610     const Function *SF = I;   // SrcFunction
611     Function *DF = 0;
612     if (SF->hasName() && !SF->hasInternalLinkage()) {
613       // Check to see if may have to link the function.
614       DF = Dest->getFunction(SF->getName());
615       if (DF && SF->getType() != DF->getType())
616         // If types don't agree because of opaque, try to resolve them
617         RecursiveResolveTypes(SF->getType(), DF->getType(), 
618                               &Dest->getTypeSymbolTable(), "");
619     }
620     
621     if (DF && DF->getType() != SF->getType()) {
622       if (DF->isDeclaration() && !SF->isDeclaration()) {
623         // We have a definition of the same name but different type in the
624         // source module. Copy the prototype to the destination and replace
625         // uses of the destination's prototype with the new prototype.
626         Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
627                                        SF->getName(), Dest);
628         CopyGVAttributes(NewDF, SF);
629
630         // Any uses of DF need to change to NewDF, with cast
631         DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
632
633         // DF will conflict with NewDF because they both had the same. We must
634         // erase this now so ForceRenaming doesn't assert because DF might
635         // not have internal linkage. 
636         DF->eraseFromParent();
637
638         // If the symbol table renamed the function, but it is an externally
639         // visible symbol, DF must be an existing function with internal 
640         // linkage.  Rename it.
641         if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
642           ForceRenaming(NewDF, SF->getName());
643
644         // Remember this mapping so uses in the source module get remapped
645         // later by RemapOperand.
646         ValueMap[SF] = NewDF;
647       } else if (SF->isDeclaration()) {
648         // We have two functions of the same name but different type and the
649         // source is a declaration while the destination is not. Any use of
650         // the source must be mapped to the destination, with a cast. 
651         ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType());
652       } else {
653         // We have two functions of the same name but different types and they
654         // are both definitions. This is an error.
655         return Error(Err, "Function '" + DF->getName() + "' defined as both '" +
656                      ToStr(SF->getFunctionType(), Src) + "' and '" +
657                      ToStr(DF->getFunctionType(), Dest) + "'");
658       }
659     } else if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
660       // Function does not already exist, simply insert an function signature
661       // identical to SF into the dest module...
662       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
663                                      SF->getName(), Dest);
664       CopyGVAttributes(NewDF, SF);
665
666       // If the LLVM runtime renamed the function, but it is an externally
667       // visible symbol, DF must be an existing function with internal linkage.
668       // Rename it.
669       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
670         ForceRenaming(NewDF, SF->getName());
671
672       // ... and remember this mapping...
673       ValueMap.insert(std::make_pair(SF, NewDF));
674     } else if (SF->isDeclaration()) {
675       // If SF is a declaration or if both SF & DF are declarations, just link 
676       // the declarations, we aren't adding anything.
677       if (SF->hasDLLImportLinkage()) {
678         if (DF->isDeclaration()) {
679           ValueMap.insert(std::make_pair(SF, DF));
680           DF->setLinkage(SF->getLinkage());          
681         }        
682       } else {
683         ValueMap.insert(std::make_pair(SF, DF));
684       }      
685     } else if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
686       // If DF is external but SF is not...
687       // Link the external functions, update linkage qualifiers
688       ValueMap.insert(std::make_pair(SF, DF));
689       DF->setLinkage(SF->getLinkage());
690     } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
691       // At this point we know that DF has LinkOnce, Weak, or External* linkage.
692       ValueMap.insert(std::make_pair(SF, DF));
693
694       // Linkonce+Weak = Weak
695       // *+External Weak = *
696       if ((DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) ||
697           DF->hasExternalWeakLinkage())
698         DF->setLinkage(SF->getLinkage());
699     } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
700       // At this point we know that SF has LinkOnce or External* linkage.
701       ValueMap.insert(std::make_pair(SF, DF));
702       if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage())
703         // Don't inherit linkonce & external weak linkage
704         DF->setLinkage(SF->getLinkage());
705     } else if (SF->getLinkage() != DF->getLinkage()) {
706         return Error(Err, "Functions named '" + SF->getName() +
707                      "' have different linkage specifiers!");
708     } else if (SF->hasExternalLinkage()) {
709       // The function is defined identically in both modules!!
710       return Error(Err, "Function '" +
711                    ToStr(SF->getFunctionType(), Src) + "':\"" +
712                    SF->getName() + "\" - Function is already defined!");
713     } else {
714       assert(0 && "Unknown linkage configuration found!");
715     }
716   }
717   return false;
718 }
719
720 // LinkFunctionBody - Copy the source function over into the dest function and
721 // fix up references to values.  At this point we know that Dest is an external
722 // function, and that Src is not.
723 static bool LinkFunctionBody(Function *Dest, Function *Src,
724                              std::map<const Value*, Value*> &ValueMap,
725                              std::string *Err) {
726   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
727
728   // Go through and convert function arguments over, remembering the mapping.
729   Function::arg_iterator DI = Dest->arg_begin();
730   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
731        I != E; ++I, ++DI) {
732     DI->setName(I->getName());  // Copy the name information over...
733
734     // Add a mapping to our local map
735     ValueMap.insert(std::make_pair(I, DI));
736   }
737
738   // Splice the body of the source function into the dest function.
739   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
740
741   // At this point, all of the instructions and values of the function are now
742   // copied over.  The only problem is that they are still referencing values in
743   // the Source function as operands.  Loop through all of the operands of the
744   // functions and patch them up to point to the local versions...
745   //
746   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
747     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
748       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
749            OI != OE; ++OI)
750         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
751           *OI = RemapOperand(*OI, ValueMap);
752
753   // There is no need to map the arguments anymore.
754   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
755        I != E; ++I)
756     ValueMap.erase(I);
757
758   return false;
759 }
760
761
762 // LinkFunctionBodies - Link in the function bodies that are defined in the
763 // source module into the DestModule.  This consists basically of copying the
764 // function over and fixing up references to values.
765 static bool LinkFunctionBodies(Module *Dest, Module *Src,
766                                std::map<const Value*, Value*> &ValueMap,
767                                std::string *Err) {
768
769   // Loop over all of the functions in the src module, mapping them over as we
770   // go
771   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
772     if (!SF->isDeclaration()) {               // No body if function is external
773       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
774
775       // DF not external SF external?
776       if (DF->isDeclaration())
777         // Only provide the function body if there isn't one already.
778         if (LinkFunctionBody(DF, SF, ValueMap, Err))
779           return true;
780     }
781   }
782   return false;
783 }
784
785 // LinkAppendingVars - If there were any appending global variables, link them
786 // together now.  Return true on error.
787 static bool LinkAppendingVars(Module *M,
788                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
789                               std::string *ErrorMsg) {
790   if (AppendingVars.empty()) return false; // Nothing to do.
791
792   // Loop over the multimap of appending vars, processing any variables with the
793   // same name, forming a new appending global variable with both of the
794   // initializers merged together, then rewrite references to the old variables
795   // and delete them.
796   std::vector<Constant*> Inits;
797   while (AppendingVars.size() > 1) {
798     // Get the first two elements in the map...
799     std::multimap<std::string,
800       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
801
802     // If the first two elements are for different names, there is no pair...
803     // Otherwise there is a pair, so link them together...
804     if (First->first == Second->first) {
805       GlobalVariable *G1 = First->second, *G2 = Second->second;
806       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
807       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
808
809       // Check to see that they two arrays agree on type...
810       if (T1->getElementType() != T2->getElementType())
811         return Error(ErrorMsg,
812          "Appending variables with different element types need to be linked!");
813       if (G1->isConstant() != G2->isConstant())
814         return Error(ErrorMsg,
815                      "Appending variables linked with different const'ness!");
816
817       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
818       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
819
820       G1->setName("");   // Clear G1's name in case of a conflict!
821       
822       // Create the new global variable...
823       GlobalVariable *NG =
824         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
825                            /*init*/0, First->first, M, G1->isThreadLocal());
826
827       // Merge the initializer...
828       Inits.reserve(NewSize);
829       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
830         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
831           Inits.push_back(I->getOperand(i));
832       } else {
833         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
834         Constant *CV = Constant::getNullValue(T1->getElementType());
835         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
836           Inits.push_back(CV);
837       }
838       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
839         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
840           Inits.push_back(I->getOperand(i));
841       } else {
842         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
843         Constant *CV = Constant::getNullValue(T2->getElementType());
844         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
845           Inits.push_back(CV);
846       }
847       NG->setInitializer(ConstantArray::get(NewType, Inits));
848       Inits.clear();
849
850       // Replace any uses of the two global variables with uses of the new
851       // global...
852
853       // FIXME: This should rewrite simple/straight-forward uses such as
854       // getelementptr instructions to not use the Cast!
855       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
856       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
857
858       // Remove the two globals from the module now...
859       M->getGlobalList().erase(G1);
860       M->getGlobalList().erase(G2);
861
862       // Put the new global into the AppendingVars map so that we can handle
863       // linking of more than two vars...
864       Second->second = NG;
865     }
866     AppendingVars.erase(First);
867   }
868
869   return false;
870 }
871
872
873 // LinkModules - This function links two modules together, with the resulting
874 // left module modified to be the composite of the two input modules.  If an
875 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
876 // the problem.  Upon failure, the Dest module could be in a modified state, and
877 // shouldn't be relied on to be consistent.
878 bool
879 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
880   assert(Dest != 0 && "Invalid Destination module");
881   assert(Src  != 0 && "Invalid Source Module");
882
883   if (Dest->getDataLayout().empty()) {
884     if (!Src->getDataLayout().empty()) {
885       Dest->setDataLayout(Src->getDataLayout());
886     } else {
887       std::string DataLayout;
888
889       if (Dest->getEndianness() == Module::AnyEndianness)
890         if (Src->getEndianness() == Module::BigEndian)
891           DataLayout.append("E");
892         else if (Src->getEndianness() == Module::LittleEndian)
893           DataLayout.append("e");
894       if (Dest->getPointerSize() == Module::AnyPointerSize)
895         if (Src->getPointerSize() == Module::Pointer64)
896           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
897         else if (Src->getPointerSize() == Module::Pointer32)
898           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
899       Dest->setDataLayout(DataLayout);
900     }
901   }
902
903   // COpy the target triple from the source to dest if the dest's is empty
904   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
905     Dest->setTargetTriple(Src->getTargetTriple());
906       
907   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
908       Src->getDataLayout() != Dest->getDataLayout())
909     cerr << "WARNING: Linking two modules of different data layouts!\n";
910   if (!Src->getTargetTriple().empty() &&
911       Dest->getTargetTriple() != Src->getTargetTriple())
912     cerr << "WARNING: Linking two modules of different target triples!\n";
913
914   // Append the module inline asm string
915   if (!Src->getModuleInlineAsm().empty()) {
916     if (Dest->getModuleInlineAsm().empty())
917       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
918     else
919       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
920                                Src->getModuleInlineAsm());
921   }
922   
923   // Update the destination module's dependent libraries list with the libraries
924   // from the source module. There's no opportunity for duplicates here as the
925   // Module ensures that duplicate insertions are discarded.
926   Module::lib_iterator SI = Src->lib_begin();
927   Module::lib_iterator SE = Src->lib_end();
928   while ( SI != SE ) {
929     Dest->addLibrary(*SI);
930     ++SI;
931   }
932
933   // LinkTypes - Go through the symbol table of the Src module and see if any
934   // types are named in the src module that are not named in the Dst module.
935   // Make sure there are no type name conflicts.
936   if (LinkTypes(Dest, Src, ErrorMsg)) 
937     return true;
938
939   // ValueMap - Mapping of values from what they used to be in Src, to what they
940   // are now in Dest.
941   std::map<const Value*, Value*> ValueMap;
942
943   // AppendingVars - Keep track of global variables in the destination module
944   // with appending linkage.  After the module is linked together, they are
945   // appended and the module is rewritten.
946   std::multimap<std::string, GlobalVariable *> AppendingVars;
947   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
948        I != E; ++I) {
949     // Add all of the appending globals already in the Dest module to
950     // AppendingVars.
951     if (I->hasAppendingLinkage())
952       AppendingVars.insert(std::make_pair(I->getName(), I));
953   }
954
955   // Insert all of the globals in src into the Dest module... without linking
956   // initializers (which could refer to functions not yet mapped over).
957   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
958     return true;
959
960   // Link the functions together between the two modules, without doing function
961   // bodies... this just adds external function prototypes to the Dest
962   // function...  We do this so that when we begin processing function bodies,
963   // all of the global values that may be referenced are available in our
964   // ValueMap.
965   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
966     return true;
967
968   // Update the initializers in the Dest module now that all globals that may
969   // be referenced are in Dest.
970   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
971
972   // Link in the function bodies that are defined in the source module into the
973   // DestModule.  This consists basically of copying the function over and
974   // fixing up references to values.
975   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
976
977   // If there were any appending global variables, link them together now.
978   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
979
980   // If the source library's module id is in the dependent library list of the
981   // destination library, remove it since that module is now linked in.
982   sys::Path modId;
983   modId.set(Src->getModuleIdentifier());
984   if (!modId.isEmpty())
985     Dest->removeLibrary(modId.getBasename());
986
987   return false;
988 }
989
990 // vim: sw=2