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