bc1a6467e5c8b8e8bfbce50e483a35fea44ab548
[oota-llvm.git] / lib / Linker / LinkModules.cpp
1 //===- Linker.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/Support/Linker.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Assembly/Writer.h"
26 #include <iostream>
27
28 using namespace llvm;
29
30 // Error - Simple wrapper function to conditionally assign to E and return true.
31 // This just makes error return conditions a little bit simpler...
32 //
33 static inline bool Error(std::string *E, const std::string &Message) {
34   if (E) *E = Message;
35   return true;
36 }
37
38 //
39 // Function: ResolveTypes()
40 //
41 // Description:
42 //  Attempt to link the two specified types together.
43 //
44 // Inputs:
45 //  DestTy - The type to which we wish to resolve.
46 //  SrcTy  - The original type which we want to resolve.
47 //  Name   - The name of the type.
48 //
49 // Outputs:
50 //  DestST - The symbol table in which the new type should be placed.
51 //
52 // Return value:
53 //  true  - There is an error and the types cannot yet be linked.
54 //  false - No errors.
55 //
56 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
57                          SymbolTable *DestST, const std::string &Name) {
58   if (DestTy == SrcTy) return false;       // If already equal, noop
59
60   // Does the type already exist in the module?
61   if (DestTy && !isa<OpaqueType>(DestTy)) {  // Yup, the type already exists...
62     if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
63       const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
64     } else {
65       return true;  // Cannot link types... neither is opaque and not-equal
66     }
67   } else {                       // Type not in dest module.  Add it now.
68     if (DestTy)                  // Type _is_ in module, just opaque...
69       const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
70                            ->refineAbstractTypeTo(SrcTy);
71     else if (!Name.empty())
72       DestST->insert(Name, const_cast<Type*>(SrcTy));
73   }
74   return false;
75 }
76
77 static const FunctionType *getFT(const PATypeHolder &TH) {
78   return cast<FunctionType>(TH.get());
79 }
80 static const StructType *getST(const PATypeHolder &TH) {
81   return cast<StructType>(TH.get());
82 }
83
84 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
85 // recurses down into derived types, merging the used types if the parent types
86 // are compatible.
87 //
88 static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
89                                    const PATypeHolder &SrcTy,
90                                    SymbolTable *DestST, const std::string &Name,
91                 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
92   const Type *SrcTyT = SrcTy.get();
93   const Type *DestTyT = DestTy.get();
94   if (DestTyT == SrcTyT) return false;       // If already equal, noop
95   
96   // If we found our opaque type, resolve it now!
97   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
98     return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
99   
100   // Two types cannot be resolved together if they are of different primitive
101   // type.  For example, we cannot resolve an int to a float.
102   if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
103
104   // Otherwise, resolve the used type used by this derived type...
105   switch (DestTyT->getTypeID()) {
106   case Type::FunctionTyID: {
107     if (cast<FunctionType>(DestTyT)->isVarArg() !=
108         cast<FunctionType>(SrcTyT)->isVarArg() ||
109         cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
110         cast<FunctionType>(SrcTyT)->getNumContainedTypes())
111       return true;
112     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
113       if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
114                                  getFT(SrcTy)->getContainedType(i), DestST, "",
115                                  Pointers))
116         return true;
117     return false;
118   }
119   case Type::StructTyID: {
120     if (getST(DestTy)->getNumContainedTypes() != 
121         getST(SrcTy)->getNumContainedTypes()) return 1;
122     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
123       if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
124                                  getST(SrcTy)->getContainedType(i), DestST, "",
125                                  Pointers))
126         return true;
127     return false;
128   }
129   case Type::ArrayTyID: {
130     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
131     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
132     if (DAT->getNumElements() != SAT->getNumElements()) return true;
133     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
134                                   DestST, "", Pointers);
135   }
136   case Type::PointerTyID: {
137     // If this is a pointer type, check to see if we have already seen it.  If
138     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
139     // an associative container for this search, because the type pointers (keys
140     // in the container) change whenever types get resolved...
141     //
142     for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
143       if (Pointers[i].first == DestTy)
144         return Pointers[i].second != SrcTy;
145
146     // Otherwise, add the current pointers to the vector to stop recursion on
147     // this pair.
148     Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
149     bool Result =
150       RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
151                              cast<PointerType>(SrcTy.get())->getElementType(),
152                              DestST, "", Pointers);
153     Pointers.pop_back();
154     return Result;
155   }
156   default: assert(0 && "Unexpected type!"); return true;
157   }  
158 }
159
160 static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
161                                   const PATypeHolder &SrcTy,
162                                   SymbolTable *DestST, const std::string &Name){
163   std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
164   return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
165 }
166
167
168 // LinkTypes - Go through the symbol table of the Src module and see if any
169 // types are named in the src module that are not named in the Dst module.
170 // Make sure there are no type name conflicts.
171 //
172 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
173   SymbolTable       *DestST = &Dest->getSymbolTable();
174   const SymbolTable *SrcST  = &Src->getSymbolTable();
175
176   // Look for a type plane for Type's...
177   SymbolTable::type_const_iterator TI = SrcST->type_begin();
178   SymbolTable::type_const_iterator TE = SrcST->type_end();
179   if (TI == TE) return false;  // No named types, do nothing.
180
181   // Some types cannot be resolved immediately because they depend on other
182   // types being resolved to each other first.  This contains a list of types we
183   // are waiting to recheck.
184   std::vector<std::string> DelayedTypesToResolve;
185
186   for ( ; TI != TE; ++TI ) {
187     const std::string &Name = TI->first;
188     const Type *RHS = TI->second;
189
190     // Check to see if this type name is already in the dest module...
191     Type *Entry = DestST->lookupType(Name);
192
193     if (ResolveTypes(Entry, RHS, DestST, Name)) {
194       // They look different, save the types 'till later to resolve.
195       DelayedTypesToResolve.push_back(Name);
196     }
197   }
198
199   // Iteratively resolve types while we can...
200   while (!DelayedTypesToResolve.empty()) {
201     // Loop over all of the types, attempting to resolve them if possible...
202     unsigned OldSize = DelayedTypesToResolve.size();
203
204     // Try direct resolution by name...
205     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
206       const std::string &Name = DelayedTypesToResolve[i];
207       Type *T1 = SrcST->lookupType(Name);
208       Type *T2 = DestST->lookupType(Name);
209       if (!ResolveTypes(T2, T1, DestST, Name)) {
210         // We are making progress!
211         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
212         --i;
213       }
214     }
215
216     // Did we not eliminate any types?
217     if (DelayedTypesToResolve.size() == OldSize) {
218       // Attempt to resolve subelements of types.  This allows us to merge these
219       // two types: { int* } and { opaque* }
220       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
221         const std::string &Name = DelayedTypesToResolve[i];
222         PATypeHolder T1(SrcST->lookupType(Name));
223         PATypeHolder T2(DestST->lookupType(Name));
224
225         if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
226           // We are making progress!
227           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
228           
229           // Go back to the main loop, perhaps we can resolve directly by name
230           // now...
231           break;
232         }
233       }
234
235       // If we STILL cannot resolve the types, then there is something wrong.
236       // Report the warning and delete one of the names.
237       if (DelayedTypesToResolve.size() == OldSize) {
238         const std::string &Name = DelayedTypesToResolve.back();
239         
240         const Type *T1 = SrcST->lookupType(Name);
241         const Type *T2 = DestST->lookupType(Name);
242         std::cerr << "WARNING: Type conflict between types named '" << Name
243                   <<  "'.\n    Src='";
244         WriteTypeSymbolic(std::cerr, T1, Src);
245         std::cerr << "'.\n   Dest='";
246         WriteTypeSymbolic(std::cerr, T2, Dest);
247         std::cerr << "'\n";
248
249         // Remove the symbol name from the destination.
250         DelayedTypesToResolve.pop_back();
251       }
252     }
253   }
254
255
256   return false;
257 }
258
259 static void PrintMap(const std::map<const Value*, Value*> &M) {
260   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
261        I != E; ++I) {
262     std::cerr << " Fr: " << (void*)I->first << " ";
263     I->first->dump();
264     std::cerr << " To: " << (void*)I->second << " ";
265     I->second->dump();
266     std::cerr << "\n";
267   }
268 }
269
270
271 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
272 // module to another.  This is somewhat sophisticated in that it can
273 // automatically handle constant references correctly as well...
274 //
275 static Value *RemapOperand(const Value *In,
276                            std::map<const Value*, Value*> &LocalMap,
277                            std::map<const Value*, Value*> *GlobalMap) {
278   std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
279   if (I != LocalMap.end()) return I->second;
280
281   if (GlobalMap) {
282     I = GlobalMap->find(In);
283     if (I != GlobalMap->end()) return I->second;
284   }
285
286   // Check to see if it's a constant that we are interesting in transforming...
287   if (const Constant *CPV = dyn_cast<Constant>(In)) {
288     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
289         isa<ConstantAggregateZero>(CPV))
290       return const_cast<Constant*>(CPV);   // Simple constants stay identical...
291
292     Constant *Result = 0;
293
294     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
295       const std::vector<Use> &Ops = CPA->getValues();
296       std::vector<Constant*> Operands(Ops.size());
297       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
298         Operands[i] = 
299           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
300       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
301     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
302       const std::vector<Use> &Ops = CPS->getValues();
303       std::vector<Constant*> Operands(Ops.size());
304       for (unsigned i = 0; i < Ops.size(); ++i)
305         Operands[i] = 
306           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
307       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
308     } else if (isa<ConstantPointerNull>(CPV)) {
309       Result = const_cast<Constant*>(CPV);
310     } else if (isa<GlobalValue>(CPV)) {
311       Result = cast<Constant>(RemapOperand(CPV, LocalMap, GlobalMap));
312     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
313       if (CE->getOpcode() == Instruction::GetElementPtr) {
314         Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
315         std::vector<Constant*> Indices;
316         Indices.reserve(CE->getNumOperands()-1);
317         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
318           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
319                                                         LocalMap, GlobalMap)));
320
321         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
322       } else if (CE->getNumOperands() == 1) {
323         // Cast instruction
324         assert(CE->getOpcode() == Instruction::Cast);
325         Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
326         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
327       } else if (CE->getNumOperands() == 3) {
328         // Select instruction
329         assert(CE->getOpcode() == Instruction::Select);
330         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
331         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
332         Value *V3 = RemapOperand(CE->getOperand(2), LocalMap, GlobalMap);
333         Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
334                                          cast<Constant>(V3));
335       } else if (CE->getNumOperands() == 2) {
336         // Binary operator...
337         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
338         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
339
340         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
341                                    cast<Constant>(V2));
342       } else {
343         assert(0 && "Unknown constant expr type!");
344       }
345
346     } else {
347       assert(0 && "Unknown type of derived type constant value!");
348     }
349
350     // Cache the mapping in our local map structure...
351     if (GlobalMap)
352       GlobalMap->insert(std::make_pair(In, Result));
353     else
354       LocalMap.insert(std::make_pair(In, Result));
355     return Result;
356   }
357
358   std::cerr << "XXX LocalMap: \n";
359   PrintMap(LocalMap);
360
361   if (GlobalMap) {
362     std::cerr << "XXX GlobalMap: \n";
363     PrintMap(*GlobalMap);
364   }
365
366   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
367   assert(0 && "Couldn't remap value!");
368   return 0;
369 }
370
371 /// FindGlobalNamed - Look in the specified symbol table for a global with the
372 /// specified name and type.  If an exactly matching global does not exist, see
373 /// if there is a global which is "type compatible" with the specified
374 /// name/type.  This allows us to resolve things like '%x = global int*' with
375 /// '%x = global opaque*'.
376 ///
377 static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
378                                     SymbolTable *ST) {
379   // See if an exact match exists in the symbol table...
380   if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
381   
382   // It doesn't exist exactly, scan through all of the type planes in the symbol
383   // table, checking each of them for a type-compatible version.
384   //
385   for (SymbolTable::plane_iterator PI = ST->plane_begin(), PE = ST->plane_end();
386        PI != PE; ++PI) {
387     // Does this type plane contain an entry with the specified name?
388     SymbolTable::ValueMap &VM = PI->second;
389     SymbolTable::value_iterator VI = VM.find(Name);
390
391     if (VI != VM.end()) {
392       // Ensure that this type if placed correctly into the symbol table.
393       GlobalValue *ValPtr = cast<GlobalValue>(VI->second);
394       assert(ValPtr->getType() == PI->first && "Type conflict!");
395       
396       // Determine whether we can fold the two types together, resolving them.
397       // If so, we can use this value.
398       if (!ValPtr->hasInternalLinkage() &&
399           !RecursiveResolveTypes(Ty, PI->first, ST, ""))
400         return ValPtr;
401     }
402   }
403   return 0;  // Otherwise, nothing could be found.
404 }
405
406
407 // LinkGlobals - Loop through the global variables in the src module and merge
408 // them into the dest module.
409 //
410 static bool LinkGlobals(Module *Dest, const Module *Src,
411                         std::map<const Value*, Value*> &ValueMap,
412                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
413                         std::string *Err) {
414   // We will need a module level symbol table if the src module has a module
415   // level symbol table...
416   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
417   
418   // Loop over all of the globals in the src module, mapping them over as we go
419   //
420   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
421     const GlobalVariable *SGV = I;
422     GlobalVariable *DGV = 0;
423     if (SGV->hasName() && !SGV->hasInternalLinkage()) {
424       // A same named thing is a global variable, because the only two things
425       // that may be in a module level symbol table are Global Vars and
426       // Functions, and they both have distinct, nonoverlapping, possible types.
427       // 
428       DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(), 
429                                                          SGV->getType(), ST));
430     }
431
432     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
433            "Global must either be external or have an initializer!");
434
435     bool SGExtern = SGV->isExternal();
436     bool DGExtern = DGV ? DGV->isExternal() : false;
437
438     if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
439       // No linking to be performed, simply create an identical version of the
440       // symbol over in the dest module... the initializer will be filled in
441       // later by LinkGlobalInits...
442       //
443       GlobalVariable *NewDGV =
444         new GlobalVariable(SGV->getType()->getElementType(),
445                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
446                            SGV->getName(), Dest);
447
448       // If the LLVM runtime renamed the global, but it is an externally visible
449       // symbol, DGV must be an existing global with internal linkage.  Rename
450       // it.
451       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
452         assert(DGV && DGV->getName() == SGV->getName() &&
453                DGV->hasInternalLinkage());
454         DGV->setName("");
455         NewDGV->setName(SGV->getName());  // Force the name back
456         DGV->setName(SGV->getName());     // This will cause a renaming
457         assert(NewDGV->getName() == SGV->getName() &&
458                DGV->getName() != SGV->getName());
459       }
460
461       // Make sure to remember this mapping...
462       ValueMap.insert(std::make_pair(SGV, NewDGV));
463       if (SGV->hasAppendingLinkage())
464         // Keep track that this is an appending variable...
465         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
466
467     } else if (SGV->isExternal()) {
468       // If SGV is external or if both SGV & DGV are external..  Just link the
469       // external globals, we aren't adding anything.
470       ValueMap.insert(std::make_pair(SGV, DGV));
471
472     } else if (DGV->isExternal()) {   // If DGV is external but SGV is not...
473       ValueMap.insert(std::make_pair(SGV, DGV));
474       DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
475     } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
476       // At this point we know that DGV has LinkOnce, Appending, Weak, or
477       // External linkage.  If DGV is Appending, this is an error.
478       if (DGV->hasAppendingLinkage())
479         return Error(Err, "Linking globals named '" + SGV->getName() +
480                      " ' with 'weak' and 'appending' linkage is not allowed!");
481
482       if (SGV->isConstant() != DGV->isConstant())
483         return Error(Err, "Global Variable Collision on '" + 
484                      SGV->getType()->getDescription() + " %" + SGV->getName() +
485                      "' - Global variables differ in const'ness");
486
487       // Otherwise, just perform the link.
488       ValueMap.insert(std::make_pair(SGV, DGV));
489
490       // Linkonce+Weak = Weak
491       if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
492         DGV->setLinkage(SGV->getLinkage());
493
494     } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
495       // At this point we know that SGV has LinkOnce, Appending, or External
496       // linkage.  If SGV is Appending, this is an error.
497       if (SGV->hasAppendingLinkage())
498         return Error(Err, "Linking globals named '" + SGV->getName() +
499                      " ' with 'weak' and 'appending' linkage is not allowed!");
500
501       if (SGV->isConstant() != DGV->isConstant())
502         return Error(Err, "Global Variable Collision on '" + 
503                      SGV->getType()->getDescription() + " %" + SGV->getName() +
504                      "' - Global variables differ in const'ness");
505
506       if (!SGV->hasLinkOnceLinkage())
507         DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
508       ValueMap.insert(std::make_pair(SGV, DGV));
509   
510     } else if (SGV->getLinkage() != DGV->getLinkage()) {
511       return Error(Err, "Global variables named '" + SGV->getName() +
512                    "' have different linkage specifiers!");
513     } else if (SGV->hasExternalLinkage()) {
514       // Allow linking two exactly identical external global variables...
515       if (SGV->isConstant() != DGV->isConstant())
516         return Error(Err, "Global Variable Collision on '" + 
517                      SGV->getType()->getDescription() + " %" + SGV->getName() +
518                      "' - Global variables differ in const'ness");
519
520       if (SGV->getInitializer() != DGV->getInitializer())
521         return Error(Err, "Global Variable Collision on '" + 
522                      SGV->getType()->getDescription() + " %" + SGV->getName() +
523                     "' - External linkage globals have different initializers");
524
525       ValueMap.insert(std::make_pair(SGV, DGV));
526     } else if (SGV->hasAppendingLinkage()) {
527       // No linking is performed yet.  Just insert a new copy of the global, and
528       // keep track of the fact that it is an appending variable in the
529       // AppendingVars map.  The name is cleared out so that no linkage is
530       // performed.
531       GlobalVariable *NewDGV =
532         new GlobalVariable(SGV->getType()->getElementType(),
533                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
534                            "", Dest);
535
536       // Make sure to remember this mapping...
537       ValueMap.insert(std::make_pair(SGV, NewDGV));
538
539       // Keep track that this is an appending variable...
540       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
541     } else {
542       assert(0 && "Unknown linkage!");
543     }
544   }
545   return false;
546 }
547
548
549 // LinkGlobalInits - Update the initializers in the Dest module now that all
550 // globals that may be referenced are in Dest.
551 //
552 static bool LinkGlobalInits(Module *Dest, const Module *Src,
553                             std::map<const Value*, Value*> &ValueMap,
554                             std::string *Err) {
555
556   // Loop over all of the globals in the src module, mapping them over as we go
557   //
558   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
559     const GlobalVariable *SGV = I;
560
561     if (SGV->hasInitializer()) {      // Only process initialized GV's
562       // Figure out what the initializer looks like in the dest module...
563       Constant *SInit =
564         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
565
566       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
567       if (DGV->hasInitializer()) {
568         if (SGV->hasExternalLinkage()) {
569           if (DGV->getInitializer() != SInit)
570             return Error(Err, "Global Variable Collision on '" + 
571                          SGV->getType()->getDescription() +"':%"+SGV->getName()+
572                          " - Global variables have different initializers");
573         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
574           // Nothing is required, mapped values will take the new global
575           // automatically.
576         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
577           // Nothing is required, mapped values will take the new global
578           // automatically.
579         } else if (DGV->hasAppendingLinkage()) {
580           assert(0 && "Appending linkage unimplemented!");
581         } else {
582           assert(0 && "Unknown linkage!");
583         }
584       } else {
585         // Copy the initializer over now...
586         DGV->setInitializer(SInit);
587       }
588     }
589   }
590   return false;
591 }
592
593 // LinkFunctionProtos - Link the functions together between the two modules,
594 // without doing function bodies... this just adds external function prototypes
595 // to the Dest function...
596 //
597 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
598                                std::map<const Value*, Value*> &ValueMap,
599                                std::string *Err) {
600   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
601   
602   // Loop over all of the functions in the src module, mapping them over as we
603   // go
604   //
605   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
606     const Function *SF = I;   // SrcFunction
607     Function *DF = 0;
608     if (SF->hasName() && !SF->hasInternalLinkage())
609       // The same named thing is a Function, because the only two things
610       // that may be in a module level symbol table are Global Vars and
611       // Functions, and they both have distinct, nonoverlapping, possible types.
612       // 
613       DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
614                                                   ST));
615
616     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
617       // Function does not already exist, simply insert an function signature
618       // identical to SF into the dest module...
619       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
620                                      SF->getName(), Dest);
621
622       // If the LLVM runtime renamed the function, but it is an externally
623       // visible symbol, DF must be an existing function with internal linkage.
624       // Rename it.
625       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
626         assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
627         DF->setName("");
628         NewDF->setName(SF->getName());  // Force the name back
629         DF->setName(SF->getName());     // This will cause a renaming
630         assert(NewDF->getName() == SF->getName() &&
631                DF->getName() != SF->getName());
632       }
633
634       // ... and remember this mapping...
635       ValueMap.insert(std::make_pair(SF, NewDF));
636     } else if (SF->isExternal()) {
637       // If SF is external or if both SF & DF are external..  Just link the
638       // external functions, we aren't adding anything.
639       ValueMap.insert(std::make_pair(SF, DF));
640     } else if (DF->isExternal()) {   // If DF is external but SF is not...
641       // Link the external functions, update linkage qualifiers
642       ValueMap.insert(std::make_pair(SF, DF));
643       DF->setLinkage(SF->getLinkage());
644
645     } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
646       // At this point we know that DF has LinkOnce, Weak, or External linkage.
647       ValueMap.insert(std::make_pair(SF, DF));
648
649       // Linkonce+Weak = Weak
650       if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
651         DF->setLinkage(SF->getLinkage());
652
653     } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
654       // At this point we know that SF has LinkOnce or External linkage.
655       ValueMap.insert(std::make_pair(SF, DF));
656       if (!SF->hasLinkOnceLinkage())   // Don't inherit linkonce linkage
657         DF->setLinkage(SF->getLinkage());
658
659     } else if (SF->getLinkage() != DF->getLinkage()) {
660       return Error(Err, "Functions named '" + SF->getName() +
661                    "' have different linkage specifiers!");
662     } else if (SF->hasExternalLinkage()) {
663       // The function is defined in both modules!!
664       return Error(Err, "Function '" + 
665                    SF->getFunctionType()->getDescription() + "':\"" + 
666                    SF->getName() + "\" - Function is already defined!");
667     } else {
668       assert(0 && "Unknown linkage configuration found!");
669     }
670   }
671   return false;
672 }
673
674 // LinkFunctionBody - Copy the source function over into the dest function and
675 // fix up references to values.  At this point we know that Dest is an external
676 // function, and that Src is not.
677 //
678 static bool LinkFunctionBody(Function *Dest, const Function *Src,
679                              std::map<const Value*, Value*> &GlobalMap,
680                              std::string *Err) {
681   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
682   std::map<const Value*, Value*> LocalMap;   // Map for function local values
683
684   // Go through and convert function arguments over...
685   Function::aiterator DI = Dest->abegin();
686   for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
687        I != E; ++I, ++DI) {
688     DI->setName(I->getName());  // Copy the name information over...
689
690     // Add a mapping to our local map
691     LocalMap.insert(std::make_pair(I, DI));
692   }
693
694   // Loop over all of the basic blocks, copying the instructions over...
695   //
696   for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
697     // Create new basic block and add to mapping and the Dest function...
698     BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
699     LocalMap.insert(std::make_pair(I, DBB));
700
701     // Loop over all of the instructions in the src basic block, copying them
702     // over.  Note that this is broken in a strict sense because the cloned
703     // instructions will still be referencing values in the Src module, not
704     // the remapped values.  In our case, however, we will not get caught and 
705     // so we can delay patching the values up until later...
706     //
707     for (BasicBlock::const_iterator II = I->begin(), IE = I->end(); 
708          II != IE; ++II) {
709       Instruction *DI = II->clone();
710       DI->setName(II->getName());
711       DBB->getInstList().push_back(DI);
712       LocalMap.insert(std::make_pair(II, DI));
713     }
714   }
715
716   // At this point, all of the instructions and values of the function are now
717   // copied over.  The only problem is that they are still referencing values in
718   // the Source function as operands.  Loop through all of the operands of the
719   // functions and patch them up to point to the local versions...
720   //
721   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
722     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
723       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
724            OI != OE; ++OI)
725         *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
726
727   return false;
728 }
729
730
731 // LinkFunctionBodies - Link in the function bodies that are defined in the
732 // source module into the DestModule.  This consists basically of copying the
733 // function over and fixing up references to values.
734 //
735 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
736                                std::map<const Value*, Value*> &ValueMap,
737                                std::string *Err) {
738
739   // Loop over all of the functions in the src module, mapping them over as we
740   // go
741   //
742   for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
743     if (!SF->isExternal()) {                  // No body if function is external
744       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
745
746       // DF not external SF external?
747       if (DF->isExternal()) {
748         // Only provide the function body if there isn't one already.
749         if (LinkFunctionBody(DF, SF, ValueMap, Err))
750           return true;
751       }
752     }
753   }
754   return false;
755 }
756
757 // LinkAppendingVars - If there were any appending global variables, link them
758 // together now.  Return true on error.
759 //
760 static bool LinkAppendingVars(Module *M,
761                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
762                               std::string *ErrorMsg) {
763   if (AppendingVars.empty()) return false; // Nothing to do.
764   
765   // Loop over the multimap of appending vars, processing any variables with the
766   // same name, forming a new appending global variable with both of the
767   // initializers merged together, then rewrite references to the old variables
768   // and delete them.
769   //
770   std::vector<Constant*> Inits;
771   while (AppendingVars.size() > 1) {
772     // Get the first two elements in the map...
773     std::multimap<std::string,
774       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
775
776     // If the first two elements are for different names, there is no pair...
777     // Otherwise there is a pair, so link them together...
778     if (First->first == Second->first) {
779       GlobalVariable *G1 = First->second, *G2 = Second->second;
780       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
781       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
782       
783       // Check to see that they two arrays agree on type...
784       if (T1->getElementType() != T2->getElementType())
785         return Error(ErrorMsg,
786          "Appending variables with different element types need to be linked!");
787       if (G1->isConstant() != G2->isConstant())
788         return Error(ErrorMsg,
789                      "Appending variables linked with different const'ness!");
790
791       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
792       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
793
794       // Create the new global variable...
795       GlobalVariable *NG =
796         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
797                            /*init*/0, First->first, M);
798
799       // Merge the initializer...
800       Inits.reserve(NewSize);
801       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
802         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
803           Inits.push_back(cast<Constant>(I->getValues()[i]));
804       } else {
805         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
806         Constant *CV = Constant::getNullValue(T1->getElementType());
807         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
808           Inits.push_back(CV);
809       }
810       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
811         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
812           Inits.push_back(cast<Constant>(I->getValues()[i]));
813       } else {
814         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
815         Constant *CV = Constant::getNullValue(T2->getElementType());
816         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
817           Inits.push_back(CV);
818       }
819       NG->setInitializer(ConstantArray::get(NewType, Inits));
820       Inits.clear();
821
822       // Replace any uses of the two global variables with uses of the new
823       // global...
824
825       // FIXME: This should rewrite simple/straight-forward uses such as
826       // getelementptr instructions to not use the Cast!
827       G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
828       G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
829
830       // Remove the two globals from the module now...
831       M->getGlobalList().erase(G1);
832       M->getGlobalList().erase(G2);
833
834       // Put the new global into the AppendingVars map so that we can handle
835       // linking of more than two vars...
836       Second->second = NG;
837     }
838     AppendingVars.erase(First);
839   }
840
841   return false;
842 }
843
844
845 // LinkModules - This function links two modules together, with the resulting
846 // left module modified to be the composite of the two input modules.  If an
847 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
848 // the problem.  Upon failure, the Dest module could be in a modified state, and
849 // shouldn't be relied on to be consistent.
850 //
851 bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
852   if (Dest->getEndianness() == Module::AnyEndianness)
853     Dest->setEndianness(Src->getEndianness());
854   if (Dest->getPointerSize() == Module::AnyPointerSize)
855     Dest->setPointerSize(Src->getPointerSize());
856
857   if (Src->getEndianness() != Module::AnyEndianness &&
858       Dest->getEndianness() != Src->getEndianness())
859     std::cerr << "WARNING: Linking two modules of different endianness!\n";
860   if (Src->getPointerSize() != Module::AnyPointerSize &&
861       Dest->getPointerSize() != Src->getPointerSize())
862     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
863
864   // LinkTypes - Go through the symbol table of the Src module and see if any
865   // types are named in the src module that are not named in the Dst module.
866   // Make sure there are no type name conflicts.
867   //
868   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
869
870   // ValueMap - Mapping of values from what they used to be in Src, to what they
871   // are now in Dest.
872   //
873   std::map<const Value*, Value*> ValueMap;
874
875   // AppendingVars - Keep track of global variables in the destination module
876   // with appending linkage.  After the module is linked together, they are
877   // appended and the module is rewritten.
878   //
879   std::multimap<std::string, GlobalVariable *> AppendingVars;
880
881   // Add all of the appending globals already in the Dest module to
882   // AppendingVars.
883   for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
884     if (I->hasAppendingLinkage())
885       AppendingVars.insert(std::make_pair(I->getName(), I));
886
887   // Insert all of the globals in src into the Dest module... without linking
888   // initializers (which could refer to functions not yet mapped over).
889   //
890   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
891
892   // Link the functions together between the two modules, without doing function
893   // bodies... this just adds external function prototypes to the Dest
894   // function...  We do this so that when we begin processing function bodies,
895   // all of the global values that may be referenced are available in our
896   // ValueMap.
897   //
898   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
899
900   // Update the initializers in the Dest module now that all globals that may
901   // be referenced are in Dest.
902   //
903   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
904
905   // Link in the function bodies that are defined in the source module into the
906   // DestModule.  This consists basically of copying the function over and
907   // fixing up references to values.
908   //
909   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
910
911   // If there were any appending global variables, link them together now.
912   //
913   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
914
915   return false;
916 }
917
918 // vim: sw=2