LinkModules.cpp revision 1bcbf8582e94eee6f151e5e2db2d04f417abf5f7
1ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
3ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//                     The LLVM Compiler Infrastructure
4ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
5ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// This file is distributed under the University of Illinois Open Source
6ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// License. See LICENSE.TXT for details.
7ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
8ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//===----------------------------------------------------------------------===//
98a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//
108a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// This file implements the LLVM module linker.
118a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//
128a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//===----------------------------------------------------------------------===//
138a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
148a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#include "llvm/Linker.h"
158a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#include "llvm/Constants.h"
168a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#include "llvm/DerivedTypes.h"
178a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#include "llvm/Module.h"
188a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#include "llvm/Support/raw_ostream.h"
198a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#include "llvm/Support/Path.h"
208a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#include "llvm/Transforms/Utils/ValueMapper.h"
218a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.comusing namespace llvm;
228a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
238a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//===----------------------------------------------------------------------===//
248a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// TypeMap implementation.
258a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//===----------------------------------------------------------------------===//
268a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
278a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.comnamespace {
288a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.comclass TypeMapTy : public ValueMapTypeRemapper {
298a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// MappedTypes - This is a mapping from a source type to a destination type
308a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// to use.
318a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  DenseMap<Type*, Type*> MappedTypes;
328a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
338a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
348a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// we speculatively add types to MappedTypes, but keep track of them here in
358a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// case we need to roll back.
368a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  SmallVector<Type*, 16> SpeculativeTypes;
378a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
388a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// DefinitionsToResolve - This is a list of non-opaque structs in the source
398a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// module that are mapped to an opaque struct in the destination module.
408a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  SmallVector<StructType*, 16> DefinitionsToResolve;
418a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.compublic:
428a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
438a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// addTypeMapping - Indicate that the specified type in the destination
448a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// module is conceptually equivalent to the specified type in the source
458a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// module.
468a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  void addTypeMapping(Type *DstTy, Type *SrcTy);
478a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
488a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
498a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// module from a type definition in the source module.
508a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  void linkDefinedTypeBodies();
518a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
528a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// get - Return the mapped type to use for the specified input type from the
538a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// source module.
548a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  Type *get(Type *SrcTy);
558a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
568a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
578a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
588a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.comprivate:
598a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  Type *getImpl(Type *T);
608a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// remapType - Implement the ValueMapTypeRemapper interface.
618a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  Type *remapType(Type *SrcTy) {
628a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return get(SrcTy);
638a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
648a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
658a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
668a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com};
678a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com}
688a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
698a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.comvoid TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
708a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  Type *&Entry = MappedTypes[SrcTy];
718a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (Entry) return;
728a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
738a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (DstTy == SrcTy) {
748a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    Entry = DstTy;
758a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return;
768a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
778a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
788a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // Check to see if these types are recursively isomorphic and establish a
798a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // mapping between them if so.
808a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (!areTypesIsomorphic(DstTy, SrcTy)) {
818a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Oops, they aren't isomorphic.  Just discard this request by rolling out
828a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // any speculative mappings we've established.
838a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
848a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      MappedTypes.erase(SpeculativeTypes[i]);
858a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
868a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  SpeculativeTypes.clear();
878a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com}
888a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
898a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com/// areTypesIsomorphic - Recursively walk this pair of types, returning true
908a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com/// if they are isomorphic, false if they are not.
918a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.combool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
928a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // Two types with differing kinds are clearly not isomorphic.
938a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
948a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
958a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // If we have an entry in the MappedTypes table, then we have our answer.
968a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  Type *&Entry = MappedTypes[SrcTy];
978a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (Entry)
988a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return Entry == DstTy;
998a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1008a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // Two identical types are clearly isomorphic.  Remember this
1018a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // non-speculatively.
102d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com  if (DstTy == SrcTy) {
1038a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    Entry = DstTy;
1048a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return true;
1058a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
1068a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1078a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // Okay, we have two types with identical kinds that we haven't seen before.
1088a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
10964cc579efa7e416c7298ed159d76b074b283c0f9senorblanco@chromium.org  // If this is an opaque struct type, special case it.
1108a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
1118a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Mapping an opaque type to any struct, just keep the dest struct.
1128a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (SSTy->isOpaque()) {
1138a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      Entry = DstTy;
1148a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      SpeculativeTypes.push_back(SrcTy);
1158a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return true;
1168a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    }
1178a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1188a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Mapping a non-opaque source type to an opaque dest.  Keep the dest, but
1198a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // fill it in later.  This doesn't need to be speculative.
1208a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (cast<StructType>(DstTy)->isOpaque()) {
1218a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      Entry = DstTy;
1228a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      DefinitionsToResolve.push_back(SSTy);
1238a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return true;
1248a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    }
1258a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
1268a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
12764cc579efa7e416c7298ed159d76b074b283c0f9senorblanco@chromium.org  // If the number of subtypes disagree between the two types, then we fail.
1288a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
12964cc579efa7e416c7298ed159d76b074b283c0f9senorblanco@chromium.org    return false;
1308a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1318a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // Fail if any of the extra properties (e.g. array size) of the type disagree.
1328a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (isa<IntegerType>(DstTy))
1338a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return false;  // bitwidth disagrees.
1348a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
1358a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
1368a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return false;
1378a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
138d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com    if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
1398a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return false;
1408a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
1418a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    StructType *SSTy = cast<StructType>(SrcTy);
1428a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (DSTy->isLiteral() != SSTy->isLiteral() ||
1438a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        DSTy->isPacked() != SSTy->isPacked())
1448a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return false;
1458a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
1468a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
1478a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return false;
1488a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1498a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
1508a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return false;
1518a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
1528a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1538a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // Otherwise, we speculate that these two types will line up and recursively
1548a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // check the subelements.
1558a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  Entry = DstTy;
1568a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  SpeculativeTypes.push_back(SrcTy);
1578a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1588a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
1598a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (!areTypesIsomorphic(DstTy->getContainedType(i),
1608a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com                            SrcTy->getContainedType(i)))
1618a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return false;
1628a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1638a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // If everything seems to have lined up, then everything is great.
1648a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  return true;
1658a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com}
1668a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1678a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
1688a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com/// module from a type definition in the source module.
1698a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.comvoid TypeMapTy::linkDefinedTypeBodies() {
1708a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  SmallVector<Type*, 16> Elements;
1718a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  SmallString<16> TmpName;
1728a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1738a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // Note that processing entries in this loop (calling 'get') can add new
1748a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  // entries to the DefinitionsToResolve vector.
17564cc579efa7e416c7298ed159d76b074b283c0f9senorblanco@chromium.org  while (!DefinitionsToResolve.empty()) {
1768a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    StructType *SrcSTy = DefinitionsToResolve.pop_back_val();
1778a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
1788a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1798a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // TypeMap is a many-to-one mapping, if there were multiple types that
1808a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // provide a body for DstSTy then previous iterations of this loop may have
1818a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // already handled it.  Just ignore this case.
1828a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (!DstSTy->isOpaque()) continue;
1838a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
1848a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1858a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Map the body of the source type over to a new body for the dest type.
1868a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    Elements.resize(SrcSTy->getNumElements());
1878a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1888a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      Elements[i] = getImpl(SrcSTy->getElementType(i));
1898a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1908a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    DstSTy->setBody(Elements, SrcSTy->isPacked());
1918a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1928a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // If DstSTy has no name or has a longer name than STy, then viciously steal
1938a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // STy's name.
1948a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (!SrcSTy->hasName()) continue;
1958a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    StringRef SrcName = SrcSTy->getName();
1968a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1978a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
1988a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
1998a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      SrcSTy->setName("");
2008a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      DstSTy->setName(TmpName.str());
2018a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      TmpName.clear();
20264cc579efa7e416c7298ed159d76b074b283c0f9senorblanco@chromium.org    }
20364cc579efa7e416c7298ed159d76b074b283c0f9senorblanco@chromium.org  }
2048a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com}
2058a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
2068a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
2078a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com/// get - Return the mapped type to use for the specified input type from the
2088a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com/// source module.
2098a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.comType *TypeMapTy::get(Type *Ty) {
2108a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  Type *Result = getImpl(Ty);
2118a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
212  // If this caused a reference to any struct type, resolve it before returning.
213  if (!DefinitionsToResolve.empty())
214    linkDefinedTypeBodies();
215  return Result;
216}
217
218/// getImpl - This is the recursive version of get().
219Type *TypeMapTy::getImpl(Type *Ty) {
220  // If we already have an entry for this type, return it.
221  Type **Entry = &MappedTypes[Ty];
222  if (*Entry) return *Entry;
223
224  // If this is not a named struct type, then just map all of the elements and
225  // then rebuild the type from inside out.
226  if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
227    // If there are no element types to map, then the type is itself.  This is
228    // true for the anonymous {} struct, things like 'float', integers, etc.
229    if (Ty->getNumContainedTypes() == 0)
230      return *Entry = Ty;
231
232    // Remap all of the elements, keeping track of whether any of them change.
233    bool AnyChange = false;
234    SmallVector<Type*, 4> ElementTypes;
235    ElementTypes.resize(Ty->getNumContainedTypes());
236    for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
237      ElementTypes[i] = getImpl(Ty->getContainedType(i));
238      AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
239    }
240
241    // If we found our type while recursively processing stuff, just use it.
242    Entry = &MappedTypes[Ty];
243    if (*Entry) return *Entry;
244
245    // If all of the element types mapped directly over, then the type is usable
246    // as-is.
247    if (!AnyChange)
248      return *Entry = Ty;
249
250    // Otherwise, rebuild a modified type.
251    switch (Ty->getTypeID()) {
252    default: assert(0 && "unknown derived type to remap");
253    case Type::ArrayTyID:
254      return *Entry = ArrayType::get(ElementTypes[0],
255                                     cast<ArrayType>(Ty)->getNumElements());
256    case Type::VectorTyID:
257      return *Entry = VectorType::get(ElementTypes[0],
258                                      cast<VectorType>(Ty)->getNumElements());
259    case Type::PointerTyID:
260      return *Entry = PointerType::get(ElementTypes[0],
261                                      cast<PointerType>(Ty)->getAddressSpace());
262    case Type::FunctionTyID:
263      return *Entry = FunctionType::get(ElementTypes[0],
264                                        makeArrayRef(ElementTypes).slice(1),
265                                        cast<FunctionType>(Ty)->isVarArg());
266    case Type::StructTyID:
267      // Note that this is only reached for anonymous structs.
268      return *Entry = StructType::get(Ty->getContext(), ElementTypes,
269                                      cast<StructType>(Ty)->isPacked());
270    }
271  }
272
273  // Otherwise, this is an unmapped named struct.  If the struct can be directly
274  // mapped over, just use it as-is.  This happens in a case when the linked-in
275  // module has something like:
276  //   %T = type {%T*, i32}
277  //   @GV = global %T* null
278  // where T does not exist at all in the destination module.
279  //
280  // The other case we watch for is when the type is not in the destination
281  // module, but that it has to be rebuilt because it refers to something that
282  // is already mapped.  For example, if the destination module has:
283  //  %A = type { i32 }
284  // and the source module has something like
285  //  %A' = type { i32 }
286  //  %B = type { %A'* }
287  //  @GV = global %B* null
288  // then we want to create a new type: "%B = type { %A*}" and have it take the
289  // pristine "%B" name from the source module.
290  //
291  // To determine which case this is, we have to recursively walk the type graph
292  // speculating that we'll be able to reuse it unmodified.  Only if this is
293  // safe would we map the entire thing over.  Because this is an optimization,
294  // and is not required for the prettiness of the linked module, we just skip
295  // it and always rebuild a type here.
296  StructType *STy = cast<StructType>(Ty);
297
298  // If the type is opaque, we can just use it directly.
299  if (STy->isOpaque())
300    return *Entry = STy;
301
302  // Otherwise we create a new type and resolve its body later.  This will be
303  // resolved by the top level of get().
304  DefinitionsToResolve.push_back(STy);
305  return *Entry = StructType::create(STy->getContext());
306}
307
308
309
310//===----------------------------------------------------------------------===//
311// ModuleLinker implementation.
312//===----------------------------------------------------------------------===//
313
314namespace {
315  /// ModuleLinker - This is an implementation class for the LinkModules
316  /// function, which is the entrypoint for this file.
317  class ModuleLinker {
318    Module *DstM, *SrcM;
319
320    TypeMapTy TypeMap;
321
322    /// ValueMap - Mapping of values from what they used to be in Src, to what
323    /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
324    /// some overhead due to the use of Value handles which the Linker doesn't
325    /// actually need, but this allows us to reuse the ValueMapper code.
326    ValueToValueMapTy ValueMap;
327
328    struct AppendingVarInfo {
329      GlobalVariable *NewGV;  // New aggregate global in dest module.
330      Constant *DstInit;      // Old initializer from dest module.
331      Constant *SrcInit;      // Old initializer from src module.
332    };
333
334    std::vector<AppendingVarInfo> AppendingVars;
335
336  public:
337    std::string ErrorMsg;
338
339    ModuleLinker(Module *dstM, Module *srcM) : DstM(dstM), SrcM(srcM) { }
340
341    bool run();
342
343  private:
344    /// emitError - Helper method for setting a message and returning an error
345    /// code.
346    bool emitError(const Twine &Message) {
347      ErrorMsg = Message.str();
348      return true;
349    }
350
351    /// getLinkageResult - This analyzes the two global values and determines
352    /// what the result will look like in the destination module.
353    bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
354                          GlobalValue::LinkageTypes &LT, bool &LinkFromSrc);
355
356    /// getLinkedToGlobal - Given a global in the source module, return the
357    /// global in the destination module that is being linked to, if any.
358    GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
359      // If the source has no name it can't link.  If it has local linkage,
360      // there is no name match-up going on.
361      if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
362        return 0;
363
364      // Otherwise see if we have a match in the destination module's symtab.
365      GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
366      if (DGV == 0) return 0;
367
368      // If we found a global with the same name in the dest module, but it has
369      // internal linkage, we are really not doing any linkage here.
370      if (DGV->hasLocalLinkage())
371        return 0;
372
373      // Otherwise, we do in fact link to the destination global.
374      return DGV;
375    }
376
377    void computeTypeMapping();
378
379    bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
380    bool linkGlobalProto(GlobalVariable *SrcGV);
381    bool linkFunctionProto(Function *SrcF);
382    bool linkAliasProto(GlobalAlias *SrcA);
383
384    void linkAppendingVarInit(const AppendingVarInfo &AVI);
385    void linkGlobalInits();
386    void linkFunctionBody(Function *Dst, Function *Src);
387    void linkAliasBodies();
388    void linkNamedMDNodes();
389  };
390}
391
392
393
394/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
395/// in the symbol table.  This is good for all clients except for us.  Go
396/// through the trouble to force this back.
397static void forceRenaming(GlobalValue *GV, StringRef Name) {
398  // If the global doesn't force its name or if it already has the right name,
399  // there is nothing for us to do.
400  if (GV->hasLocalLinkage() || GV->getName() == Name)
401    return;
402
403  Module *M = GV->getParent();
404
405  // If there is a conflict, rename the conflict.
406  if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
407    GV->takeName(ConflictGV);
408    ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
409    assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
410  } else {
411    GV->setName(Name);              // Force the name back
412  }
413}
414
415/// CopyGVAttributes - copy additional attributes (those not needed to construct
416/// a GlobalValue) from the SrcGV to the DestGV.
417static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
418  // Use the maximum alignment, rather than just copying the alignment of SrcGV.
419  unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
420  DestGV->copyAttributesFrom(SrcGV);
421  DestGV->setAlignment(Alignment);
422
423  forceRenaming(DestGV, SrcGV->getName());
424}
425
426/// getLinkageResult - This analyzes the two global values and determines what
427/// the result will look like in the destination module.  In particular, it
428/// computes the resultant linkage type, computes whether the global in the
429/// source should be copied over to the destination (replacing the existing
430/// one), and computes whether this linkage is an error or not. It also performs
431/// visibility checks: we cannot link together two symbols with different
432/// visibilities.
433bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
434                                    GlobalValue::LinkageTypes &LT,
435                                    bool &LinkFromSrc) {
436  assert(Dest && "Must have two globals being queried");
437  assert(!Src->hasLocalLinkage() &&
438         "If Src has internal linkage, Dest shouldn't be set!");
439
440  bool SrcIsDeclaration = Src->isDeclaration();
441  bool DestIsDeclaration = Dest->isDeclaration();
442
443  if (SrcIsDeclaration) {
444    // If Src is external or if both Src & Dest are external..  Just link the
445    // external globals, we aren't adding anything.
446    if (Src->hasDLLImportLinkage()) {
447      // If one of GVs has DLLImport linkage, result should be dllimport'ed.
448      if (DestIsDeclaration) {
449        LinkFromSrc = true;
450        LT = Src->getLinkage();
451      }
452    } else if (Dest->hasExternalWeakLinkage()) {
453      // If the Dest is weak, use the source linkage.
454      LinkFromSrc = true;
455      LT = Src->getLinkage();
456    } else {
457      LinkFromSrc = false;
458      LT = Dest->getLinkage();
459    }
460  } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
461    // If Dest is external but Src is not:
462    LinkFromSrc = true;
463    LT = Src->getLinkage();
464  } else if (Src->isWeakForLinker()) {
465    // At this point we know that Dest has LinkOnce, External*, Weak, Common,
466    // or DLL* linkage.
467    if (Dest->hasExternalWeakLinkage() ||
468        Dest->hasAvailableExternallyLinkage() ||
469        (Dest->hasLinkOnceLinkage() &&
470         (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
471      LinkFromSrc = true;
472      LT = Src->getLinkage();
473    } else {
474      LinkFromSrc = false;
475      LT = Dest->getLinkage();
476    }
477  } else if (Dest->isWeakForLinker()) {
478    // At this point we know that Src has External* or DLL* linkage.
479    if (Src->hasExternalWeakLinkage()) {
480      LinkFromSrc = false;
481      LT = Dest->getLinkage();
482    } else {
483      LinkFromSrc = true;
484      LT = GlobalValue::ExternalLinkage;
485    }
486  } else {
487    assert((Dest->hasExternalLinkage()  || Dest->hasDLLImportLinkage() ||
488            Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
489           (Src->hasExternalLinkage()   || Src->hasDLLImportLinkage() ||
490            Src->hasDLLExportLinkage()  || Src->hasExternalWeakLinkage()) &&
491           "Unexpected linkage type!");
492    return emitError("Linking globals named '" + Src->getName() +
493                 "': symbol multiply defined!");
494  }
495
496  // Check visibility
497  if (Src->getVisibility() != Dest->getVisibility() &&
498      !SrcIsDeclaration && !DestIsDeclaration &&
499      !Src->hasAvailableExternallyLinkage() &&
500      !Dest->hasAvailableExternallyLinkage())
501    return emitError("Linking globals named '" + Src->getName() +
502                   "': symbols have different visibilities!");
503  return false;
504}
505
506/// computeTypeMapping - Loop over all of the linked values to compute type
507/// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
508/// we have two struct types 'Foo' but one got renamed when the module was
509/// loaded into the same LLVMContext.
510void ModuleLinker::computeTypeMapping() {
511  // Incorporate globals.
512  for (Module::global_iterator I = SrcM->global_begin(),
513       E = SrcM->global_end(); I != E; ++I) {
514    GlobalValue *DGV = getLinkedToGlobal(I);
515    if (DGV == 0) continue;
516
517    if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
518      TypeMap.addTypeMapping(DGV->getType(), I->getType());
519      continue;
520    }
521
522    // Unify the element type of appending arrays.
523    ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
524    ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
525    TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
526  }
527
528  // Incorporate functions.
529  for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
530    if (GlobalValue *DGV = getLinkedToGlobal(I))
531      TypeMap.addTypeMapping(DGV->getType(), I->getType());
532  }
533
534  // Don't bother incorporating aliases, they aren't generally typed well.
535
536  // Now that we have discovered all of the type equivalences, get a body for
537  // any 'opaque' types in the dest module that are now resolved.
538  TypeMap.linkDefinedTypeBodies();
539}
540
541/// linkAppendingVarProto - If there were any appending global variables, link
542/// them together now.  Return true on error.
543bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
544                                         GlobalVariable *SrcGV) {
545
546  if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
547    return emitError("Linking globals named '" + SrcGV->getName() +
548           "': can only link appending global with another appending global!");
549
550  ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
551  ArrayType *SrcTy =
552    cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
553  Type *EltTy = DstTy->getElementType();
554
555  // Check to see that they two arrays agree on type.
556  if (EltTy != SrcTy->getElementType())
557    return emitError("Appending variables with different element types!");
558  if (DstGV->isConstant() != SrcGV->isConstant())
559    return emitError("Appending variables linked with different const'ness!");
560
561  if (DstGV->getAlignment() != SrcGV->getAlignment())
562    return emitError(
563             "Appending variables with different alignment need to be linked!");
564
565  if (DstGV->getVisibility() != SrcGV->getVisibility())
566    return emitError(
567            "Appending variables with different visibility need to be linked!");
568
569  if (DstGV->getSection() != SrcGV->getSection())
570    return emitError(
571          "Appending variables with different section name need to be linked!");
572
573  uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
574  ArrayType *NewType = ArrayType::get(EltTy, NewSize);
575
576  // Create the new global variable.
577  GlobalVariable *NG =
578    new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
579                       DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
580                       DstGV->isThreadLocal(),
581                       DstGV->getType()->getAddressSpace());
582
583  // Propagate alignment, visibility and section info.
584  CopyGVAttributes(NG, DstGV);
585
586  AppendingVarInfo AVI;
587  AVI.NewGV = NG;
588  AVI.DstInit = DstGV->getInitializer();
589  AVI.SrcInit = SrcGV->getInitializer();
590  AppendingVars.push_back(AVI);
591
592  // Replace any uses of the two global variables with uses of the new
593  // global.
594  ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
595
596  DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
597  DstGV->eraseFromParent();
598
599  // Zap the initializer in the source variable so we don't try to link it.
600  SrcGV->setInitializer(0);
601  SrcGV->setLinkage(GlobalValue::ExternalLinkage);
602  return false;
603}
604
605/// linkGlobalProto - Loop through the global variables in the src module and
606/// merge them into the dest module.
607bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
608  GlobalValue *DGV = getLinkedToGlobal(SGV);
609
610  if (DGV) {
611    // Concatenation of appending linkage variables is magic and handled later.
612    if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
613      return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
614
615    // Determine whether linkage of these two globals follows the source
616    // module's definition or the destination module's definition.
617    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
618    bool LinkFromSrc = false;
619    if (getLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc))
620      return true;
621
622    // If we're not linking from the source, then keep the definition that we
623    // have.
624    if (!LinkFromSrc) {
625      // Special case for const propagation.
626      if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
627        if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
628          DGVar->setConstant(true);
629
630      // Set calculated linkage.
631      DGV->setLinkage(NewLinkage);
632
633      // Make sure to remember this mapping.
634      ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
635
636      // Destroy the source global's initializer (and convert it to a prototype)
637      // so that we don't attempt to copy it over when processing global
638      // initializers.
639      SGV->setInitializer(0);
640      SGV->setLinkage(GlobalValue::ExternalLinkage);
641      return false;
642    }
643  }
644
645  // No linking to be performed or linking from the source: simply create an
646  // identical version of the symbol over in the dest module... the
647  // initializer will be filled in later by LinkGlobalInits.
648  GlobalVariable *NewDGV =
649    new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
650                       SGV->isConstant(), SGV->getLinkage(), /*init*/0,
651                       SGV->getName(), /*insertbefore*/0,
652                       SGV->isThreadLocal(),
653                       SGV->getType()->getAddressSpace());
654  // Propagate alignment, visibility and section info.
655  CopyGVAttributes(NewDGV, SGV);
656
657  if (DGV) {
658    DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
659    DGV->eraseFromParent();
660  }
661
662  // Make sure to remember this mapping.
663  ValueMap[SGV] = NewDGV;
664  return false;
665}
666
667/// linkFunctionProto - Link the function in the source module into the
668/// destination module if needed, setting up mapping information.
669bool ModuleLinker::linkFunctionProto(Function *SF) {
670  GlobalValue *DGV = getLinkedToGlobal(SF);
671
672  if (DGV) {
673    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
674    bool LinkFromSrc = false;
675    if (getLinkageResult(DGV, SF, NewLinkage, LinkFromSrc))
676      return true;
677
678    if (!LinkFromSrc) {
679      // Set calculated linkage
680      DGV->setLinkage(NewLinkage);
681
682      // Make sure to remember this mapping.
683      ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
684
685      // Remove the body from the source module so we don't attempt to remap it.
686      SF->deleteBody();
687      return false;
688    }
689  }
690
691  // If there is no linkage to be performed or we are linking from the source,
692  // bring SF over.
693  Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
694                                     SF->getLinkage(), SF->getName(), DstM);
695  CopyGVAttributes(NewDF, SF);
696
697  if (DGV) {
698    // Any uses of DF need to change to NewDF, with cast.
699    DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
700    DGV->eraseFromParent();
701  }
702
703  ValueMap[SF] = NewDF;
704  return false;
705}
706
707/// LinkAliasProto - Set up prototypes for any aliases that come over from the
708/// source module.
709bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
710  GlobalValue *DGV = getLinkedToGlobal(SGA);
711
712  if (DGV) {
713    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
714    bool LinkFromSrc = false;
715    if (getLinkageResult(DGV, SGA, NewLinkage, LinkFromSrc))
716      return true;
717
718    if (!LinkFromSrc) {
719      // Set calculated linkage.
720      DGV->setLinkage(NewLinkage);
721
722      // Make sure to remember this mapping.
723      ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
724
725      // Remove the body from the source module so we don't attempt to remap it.
726      SGA->setAliasee(0);
727      return false;
728    }
729  }
730
731  // If there is no linkage to be performed or we're linking from the source,
732  // bring over SGA.
733  GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
734                                       SGA->getLinkage(), SGA->getName(),
735                                       /*aliasee*/0, DstM);
736  CopyGVAttributes(NewDA, SGA);
737
738  if (DGV) {
739    // Any uses of DGV need to change to NewDA, with cast.
740    DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
741    DGV->eraseFromParent();
742  }
743
744  ValueMap[SGA] = NewDA;
745  return false;
746}
747
748void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
749  // Merge the initializer.
750  SmallVector<Constant*, 16> Elements;
751  if (ConstantArray *I = dyn_cast<ConstantArray>(AVI.DstInit)) {
752    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
753      Elements.push_back(I->getOperand(i));
754  } else {
755    assert(isa<ConstantAggregateZero>(AVI.DstInit));
756    ArrayType *DstAT = cast<ArrayType>(AVI.DstInit->getType());
757    Type *EltTy = DstAT->getElementType();
758    Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy));
759  }
760
761  Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
762  if (const ConstantArray *I = dyn_cast<ConstantArray>(SrcInit)) {
763    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
764      Elements.push_back(I->getOperand(i));
765  } else {
766    assert(isa<ConstantAggregateZero>(SrcInit));
767    ArrayType *SrcAT = cast<ArrayType>(SrcInit->getType());
768    Type *EltTy = SrcAT->getElementType();
769    Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy));
770  }
771  ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
772  AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
773}
774
775
776// linkGlobalInits - Update the initializers in the Dest module now that all
777// globals that may be referenced are in Dest.
778void ModuleLinker::linkGlobalInits() {
779  // Loop over all of the globals in the src module, mapping them over as we go
780  for (Module::const_global_iterator I = SrcM->global_begin(),
781       E = SrcM->global_end(); I != E; ++I) {
782    if (!I->hasInitializer()) continue;      // Only process initialized GV's.
783
784    // Grab destination global variable.
785    GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
786    // Figure out what the initializer looks like in the dest module.
787    DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
788                                 RF_None, &TypeMap));
789  }
790}
791
792// linkFunctionBody - Copy the source function over into the dest function and
793// fix up references to values.  At this point we know that Dest is an external
794// function, and that Src is not.
795void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
796  assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
797
798  // Go through and convert function arguments over, remembering the mapping.
799  Function::arg_iterator DI = Dst->arg_begin();
800  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
801       I != E; ++I, ++DI) {
802    DI->setName(I->getName());  // Copy the name over.
803
804    // Add a mapping to our mapping.
805    ValueMap[I] = DI;
806  }
807
808  // Splice the body of the source function into the dest function.
809  Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
810
811  // At this point, all of the instructions and values of the function are now
812  // copied over.  The only problem is that they are still referencing values in
813  // the Source function as operands.  Loop through all of the operands of the
814  // functions and patch them up to point to the local versions.
815  for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
816    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
817      RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
818
819  // There is no need to map the arguments anymore.
820  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
821       I != E; ++I)
822    ValueMap.erase(I);
823}
824
825
826void ModuleLinker::linkAliasBodies() {
827  for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
828       I != E; ++I)
829    if (Constant *Aliasee = I->getAliasee()) {
830      GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
831      DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
832    }
833}
834
835/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
836/// module.
837void ModuleLinker::linkNamedMDNodes() {
838  for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
839       E = SrcM->named_metadata_end(); I != E; ++I) {
840    NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
841    // Add Src elements into Dest node.
842    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
843      DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
844                                   RF_None, &TypeMap));
845  }
846}
847
848bool ModuleLinker::run() {
849  assert(DstM && "Null Destination module");
850  assert(SrcM && "Null Source Module");
851
852  // Inherit the target data from the source module if the destination module
853  // doesn't have one already.
854  if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
855    DstM->setDataLayout(SrcM->getDataLayout());
856
857  // Copy the target triple from the source to dest if the dest's is empty.
858  if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
859    DstM->setTargetTriple(SrcM->getTargetTriple());
860
861  if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
862      SrcM->getDataLayout() != DstM->getDataLayout())
863    errs() << "WARNING: Linking two modules of different data layouts!\n";
864  if (!SrcM->getTargetTriple().empty() &&
865      DstM->getTargetTriple() != SrcM->getTargetTriple()) {
866    errs() << "WARNING: Linking two modules of different target triples: ";
867    if (!SrcM->getModuleIdentifier().empty())
868      errs() << SrcM->getModuleIdentifier() << ": ";
869    errs() << "'" << SrcM->getTargetTriple() << "' and '"
870           << DstM->getTargetTriple() << "'\n";
871  }
872
873  // Append the module inline asm string.
874  if (!SrcM->getModuleInlineAsm().empty()) {
875    if (DstM->getModuleInlineAsm().empty())
876      DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
877    else
878      DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
879                               SrcM->getModuleInlineAsm());
880  }
881
882  // Update the destination module's dependent libraries list with the libraries
883  // from the source module. There's no opportunity for duplicates here as the
884  // Module ensures that duplicate insertions are discarded.
885  for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
886       SI != SE; ++SI)
887    DstM->addLibrary(*SI);
888
889  // If the source library's module id is in the dependent library list of the
890  // destination library, remove it since that module is now linked in.
891  StringRef ModuleId = SrcM->getModuleIdentifier();
892  if (!ModuleId.empty())
893    DstM->removeLibrary(sys::path::stem(ModuleId));
894
895
896  // Loop over all of the linked values to compute type mappings.
897  computeTypeMapping();
898
899  // Insert all of the globals in src into the DstM module... without linking
900  // initializers (which could refer to functions not yet mapped over).
901  for (Module::global_iterator I = SrcM->global_begin(),
902       E = SrcM->global_end(); I != E; ++I)
903    if (linkGlobalProto(I))
904      return true;
905
906  // Link the functions together between the two modules, without doing function
907  // bodies... this just adds external function prototypes to the DstM
908  // function...  We do this so that when we begin processing function bodies,
909  // all of the global values that may be referenced are available in our
910  // ValueMap.
911  for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
912    if (linkFunctionProto(I))
913      return true;
914
915  // If there were any aliases, link them now.
916  for (Module::alias_iterator I = SrcM->alias_begin(),
917       E = SrcM->alias_end(); I != E; ++I)
918    if (linkAliasProto(I))
919      return true;
920
921  for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
922    linkAppendingVarInit(AppendingVars[i]);
923
924  // Update the initializers in the DstM module now that all globals that may
925  // be referenced are in DstM.
926  linkGlobalInits();
927
928  // Link in the function bodies that are defined in the source module into
929  // DstM.
930  for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
931    if (SF->isDeclaration()) continue;      // No body if function is external.
932
933    linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
934  }
935
936  // Resolve all uses of aliases with aliasees.
937  linkAliasBodies();
938
939  // Remap all of the named mdnoes in Src into the DstM module. We do this
940  // after linking GlobalValues so that MDNodes that reference GlobalValues
941  // are properly remapped.
942  linkNamedMDNodes();
943
944  // Now that all of the types from the source are used, resolve any structs
945  // copied over to the dest that didn't exist there.
946  TypeMap.linkDefinedTypeBodies();
947
948  return false;
949}
950
951//===----------------------------------------------------------------------===//
952// LinkModules entrypoint.
953//===----------------------------------------------------------------------===//
954
955// LinkModules - This function links two modules together, with the resulting
956// left module modified to be the composite of the two input modules.  If an
957// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
958// the problem.  Upon failure, the Dest module could be in a modified state, and
959// shouldn't be relied on to be consistent.
960bool Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
961  ModuleLinker TheLinker(Dest, Src);
962  if (TheLinker.run()) {
963    if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
964    return true;
965  }
966
967  return false;
968}
969