#include "llvm/Linker.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/TypeSymbolTable.h"
#include "llvm/ValueSymbolTable.h"
#include "llvm/Instructions.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Path.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include "llvm/ADT/DenseMap.h"
using namespace llvm;
static inline bool Error(std::string *E, const Twine &Message) {
if (E) *E = Message.str();
return true;
}
static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
if (DestTy == SrcTy) return false; assert(DestTy && SrcTy && "Can't handle null types");
if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
} else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
} else {
return true; }
return false;
}
namespace {
class LinkerTypeMap : public AbstractTypeUser {
typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
TheMapTy TheMap;
LinkerTypeMap(const LinkerTypeMap&); void operator=(const LinkerTypeMap&); public:
LinkerTypeMap() {}
~LinkerTypeMap() {
for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
E = TheMap.end(); I != E; ++I)
I->first->removeAbstractTypeUser(this);
}
const Type *lookup(const Type *Ty) const {
TheMapTy::const_iterator I = TheMap.find(Ty);
if (I != TheMap.end()) return I->second;
return 0;
}
bool insert(const Type *Src, const Type *Dst) {
if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
return false; if (Src->isAbstract())
Src->addAbstractTypeUser(this);
return true;
}
protected:
virtual void refineAbstractType(const DerivedType *OldTy,
const Type *NewTy) {
TheMapTy::iterator I = TheMap.find(OldTy);
const Type *DstTy = I->second;
TheMap.erase(I);
if (OldTy->isAbstract())
OldTy->removeAbstractTypeUser(this);
if (NewTy->isAbstract())
insert(NewTy, DstTy);
}
virtual void typeBecameConcrete(const DerivedType *AbsTy) {
TheMap.erase(AbsTy);
AbsTy->removeAbstractTypeUser(this);
}
virtual void dump() const {
dbgs() << "AbstractTypeSet!\n";
}
};
}
static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
LinkerTypeMap &Pointers) {
if (DstTy == SrcTy) return false;
if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy())
return ResolveTypes(DstTy, SrcTy);
if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
if (!DstTy->isAbstract() && !SrcTy->isAbstract())
return true;
switch (DstTy->getTypeID()) {
default:
return true;
case Type::FunctionTyID: {
const FunctionType *DstFT = cast<FunctionType>(DstTy);
const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
if (DstFT->isVarArg() != SrcFT->isVarArg() ||
DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
return true;
PATypeHolder ST(SrcFT), DT(DstFT);
for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
return true;
}
return false;
}
case Type::StructTyID: {
const StructType *DstST = cast<StructType>(DstTy);
const StructType *SrcST = cast<StructType>(SrcTy);
if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
return true;
PATypeHolder ST(SrcST), DT(DstST);
for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
return true;
}
return false;
}
case Type::ArrayTyID: {
const ArrayType *DAT = cast<ArrayType>(DstTy);
const ArrayType *SAT = cast<ArrayType>(SrcTy);
if (DAT->getNumElements() != SAT->getNumElements()) return true;
return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Pointers);
}
case Type::VectorTyID: {
const VectorType *DVT = cast<VectorType>(DstTy);
const VectorType *SVT = cast<VectorType>(SrcTy);
if (DVT->getNumElements() != SVT->getNumElements()) return true;
return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
Pointers);
}
case Type::PointerTyID: {
const PointerType *DstPT = cast<PointerType>(DstTy);
const PointerType *SrcPT = cast<PointerType>(SrcTy);
if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
return true;
if (SrcPT->isAbstract())
if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
return ExistingDestTy != DstPT;
if (DstPT->isAbstract())
if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
return ExistingSrcTy != SrcPT;
if (DstPT->isAbstract())
Pointers.insert(DstPT, SrcPT);
if (SrcPT->isAbstract())
Pointers.insert(SrcPT, DstPT);
return RecursiveResolveTypesI(DstPT->getElementType(),
SrcPT->getElementType(), Pointers);
}
}
}
static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
LinkerTypeMap PointerTypes;
return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
}
static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
TypeSymbolTable::const_iterator TI = SrcST->begin();
TypeSymbolTable::const_iterator TE = SrcST->end();
if (TI == TE) return false;
std::vector<std::string> DelayedTypesToResolve;
for ( ; TI != TE; ++TI ) {
const std::string &Name = TI->first;
const Type *RHS = TI->second;
Type *Entry = DestST->lookup(Name);
if (Entry == 0) {
if (!Name.empty())
DestST->insert(Name, const_cast<Type*>(RHS));
} else if (ResolveTypes(Entry, RHS)) {
DelayedTypesToResolve.push_back(Name);
}
}
while (!DelayedTypesToResolve.empty()) {
unsigned OldSize = DelayedTypesToResolve.size();
for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
const std::string &Name = DelayedTypesToResolve[i];
Type *T1 = SrcST->lookup(Name);
Type *T2 = DestST->lookup(Name);
if (!ResolveTypes(T2, T1)) {
DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
--i;
}
}
if (DelayedTypesToResolve.size() == OldSize) {
for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
const std::string &Name = DelayedTypesToResolve[i];
if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
break;
}
}
if (DelayedTypesToResolve.size() == OldSize) {
DelayedTypesToResolve.pop_back();
}
}
}
return false;
}
static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
assert(GV->getName() != Name && "Can't force rename to self");
ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
assert(ConflictGV->hasLocalLinkage() &&
"Not conflicting with a static global, should link instead!");
GV->takeName(ConflictGV);
ConflictGV->setName(Name); assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
} else {
GV->setName(Name); }
}
static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
DestGV->copyAttributesFrom(SrcGV);
DestGV->setAlignment(Alignment);
}
static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
GlobalValue::LinkageTypes <, bool &LinkFromSrc,
std::string *Err) {
assert((!Dest || !Src->hasLocalLinkage()) &&
"If Src has internal linkage, Dest shouldn't be set!");
if (!Dest) {
LinkFromSrc = true;
LT = Src->getLinkage();
} else if (Src->isDeclaration()) {
if (Src->hasDLLImportLinkage()) {
if (Dest->isDeclaration()) {
LinkFromSrc = true;
LT = Src->getLinkage();
}
} else if (Dest->hasExternalWeakLinkage()) {
LinkFromSrc = true;
LT = Src->getLinkage();
} else {
LinkFromSrc = false;
LT = Dest->getLinkage();
}
} else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
LinkFromSrc = true;
LT = Src->getLinkage();
} else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
if (Src->getLinkage() != Dest->getLinkage())
return Error(Err, "Linking globals named '" + Src->getName() +
"': can only link appending global with another appending global!");
LinkFromSrc = true; LT = Src->getLinkage();
} else if (Src->isWeakForLinker()) {
if (Dest->hasExternalWeakLinkage() ||
Dest->hasAvailableExternallyLinkage() ||
(Dest->hasLinkOnceLinkage() &&
(Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
LinkFromSrc = true;
LT = Src->getLinkage();
} else {
LinkFromSrc = false;
LT = Dest->getLinkage();
}
} else if (Dest->isWeakForLinker()) {
if (Src->hasExternalWeakLinkage()) {
LinkFromSrc = false;
LT = Dest->getLinkage();
} else {
LinkFromSrc = true;
LT = GlobalValue::ExternalLinkage;
}
} else {
assert((Dest->hasExternalLinkage() ||
Dest->hasDLLImportLinkage() ||
Dest->hasDLLExportLinkage() ||
Dest->hasExternalWeakLinkage()) &&
(Src->hasExternalLinkage() ||
Src->hasDLLImportLinkage() ||
Src->hasDLLExportLinkage() ||
Src->hasExternalWeakLinkage()) &&
"Unexpected linkage type!");
return Error(Err, "Linking globals named '" + Src->getName() +
"': symbol multiply defined!");
}
if (Dest && Src->getVisibility() != Dest->getVisibility() &&
!Src->isDeclaration() && !Dest->isDeclaration() &&
!Src->hasAvailableExternallyLinkage() &&
!Dest->hasAvailableExternallyLinkage())
return Error(Err, "Linking globals named '" + Src->getName() +
"': symbols have different visibilities!");
return false;
}
static void LinkNamedMDNodes(Module *Dest, Module *Src,
ValueToValueMapTy &ValueMap) {
for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
E = Src->named_metadata_end(); I != E; ++I) {
const NamedMDNode *SrcNMD = I;
NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName());
for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i),
ValueMap)));
}
}
static bool LinkGlobals(Module *Dest, const Module *Src,
ValueToValueMapTy &ValueMap,
std::multimap<std::string, GlobalVariable *> &AppendingVars,
std::string *Err) {
ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
for (Module::const_global_iterator I = Src->global_begin(),
E = Src->global_end(); I != E; ++I) {
const GlobalVariable *SGV = I;
GlobalValue *DGV = 0;
if (SGV->hasName() && !SGV->hasLocalLinkage())
DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
if (DGV && DGV->hasLocalLinkage())
DGV = 0;
if (DGV && DGV->getType() != SGV->getType())
RecursiveResolveTypes(SGV->getType(), DGV->getType());
assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
"Global must either be external or have an initializer!");
GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
bool LinkFromSrc = false;
if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
return true;
if (DGV == 0) {
GlobalVariable *NewDGV =
new GlobalVariable(*Dest, SGV->getType()->getElementType(),
SGV->isConstant(), SGV->getLinkage(), 0,
SGV->getName(), 0, false,
SGV->getType()->getAddressSpace());
CopyGVAttributes(NewDGV, SGV);
NewDGV->setUnnamedAddr(SGV->hasUnnamedAddr());
if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
ForceRenaming(NewDGV, SGV->getName());
ValueMap[SGV] = NewDGV;
if (SGV->hasAppendingLinkage())
AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
continue;
}
bool HasUnnamedAddr = SGV->hasUnnamedAddr() && DGV->hasUnnamedAddr();
if (DGV->isDeclaration())
DGV->setVisibility(SGV->getVisibility());
if (DGV->hasAppendingLinkage()) {
GlobalVariable *NewDGV =
new GlobalVariable(*Dest, SGV->getType()->getElementType(),
SGV->isConstant(), SGV->getLinkage(), 0,
"", 0, false,
SGV->getType()->getAddressSpace());
NewDGV->setAlignment(DGV->getAlignment());
CopyGVAttributes(NewDGV, SGV);
ValueMap[SGV] = NewDGV;
AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
continue;
}
if (LinkFromSrc) {
if (isa<GlobalAlias>(DGV))
return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
"': symbol multiple defined");
GlobalVariable *NewDGV =
new GlobalVariable(*Dest, SGV->getType()->getElementType(),
SGV->isConstant(), NewLinkage, 0,
DGV->getName(), 0, false,
SGV->getType()->getAddressSpace());
NewDGV->setUnnamedAddr(HasUnnamedAddr);
CopyGVAttributes(NewDGV, SGV);
DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
DGV->getType()));
if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
Var->eraseFromParent();
else
cast<Function>(DGV)->eraseFromParent();
if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
ForceRenaming(NewDGV, SGV->getName());
NewDGV->setConstant(SGV->isConstant());
ValueMap[SGV] = NewDGV;
continue;
}
if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
DGVar->setConstant(true);
if (isa<GlobalAlias>(DGV)) {
if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
"': symbol multiple defined");
}
DGV->setLinkage(NewLinkage);
DGV->setUnnamedAddr(HasUnnamedAddr);
ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
}
return false;
}
static GlobalValue::LinkageTypes
CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
GlobalValue::LinkageTypes SL = SGV->getLinkage();
GlobalValue::LinkageTypes DL = DGV->getLinkage();
if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
return GlobalValue::ExternalLinkage;
else if (SL == GlobalValue::WeakAnyLinkage ||
DL == GlobalValue::WeakAnyLinkage)
return GlobalValue::WeakAnyLinkage;
else if (SL == GlobalValue::WeakODRLinkage ||
DL == GlobalValue::WeakODRLinkage)
return GlobalValue::WeakODRLinkage;
else if (SL == GlobalValue::InternalLinkage &&
DL == GlobalValue::InternalLinkage)
return GlobalValue::InternalLinkage;
else if (SL == GlobalValue::LinkerPrivateLinkage &&
DL == GlobalValue::LinkerPrivateLinkage)
return GlobalValue::LinkerPrivateLinkage;
else if (SL == GlobalValue::LinkerPrivateWeakLinkage &&
DL == GlobalValue::LinkerPrivateWeakLinkage)
return GlobalValue::LinkerPrivateWeakLinkage;
else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage &&
DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage)
return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
else {
assert (SL == GlobalValue::PrivateLinkage &&
DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
return GlobalValue::PrivateLinkage;
}
}
static bool LinkAlias(Module *Dest, const Module *Src,
ValueToValueMapTy &ValueMap,
std::string *Err) {
for (Module::const_alias_iterator I = Src->alias_begin(),
E = Src->alias_end(); I != E; ++I) {
const GlobalAlias *SGA = I;
const GlobalValue *SAliasee = SGA->getAliasedGlobal();
GlobalAlias *NewGA = NULL;
ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee);
assert(VMI != ValueMap.end() && "Aliasee not linked");
GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
GlobalValue* DGV = NULL;
Constant *DAliaseeConst = DAliasee;
if (SGA->getType() != DAliasee->getType())
DAliaseeConst = ConstantExpr::getBitCast(DAliasee, SGA->getType());
if (!DGV && !SGA->hasLocalLinkage()) {
DGV = Dest->getNamedAlias(SGA->getName());
if (DGV && DGV->getType() != SGA->getType())
RecursiveResolveTypes(SGA->getType(), DGV->getType());
}
if (!DGV && !SGA->hasLocalLinkage()) {
DGV = Dest->getGlobalVariable(SGA->getName());
if (DGV && DGV->getType() != SGA->getType())
RecursiveResolveTypes(SGA->getType(), DGV->getType());
}
if (!DGV && !SGA->hasLocalLinkage()) {
DGV = Dest->getFunction(SGA->getName());
if (DGV && DGV->getType() != SGA->getType())
RecursiveResolveTypes(SGA->getType(), DGV->getType());
}
if (DGV && DGV->hasLocalLinkage())
DGV = NULL;
if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
if (DAliasee == DGA->getAliasedGlobal()) {
DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
NewGA = DGA;
} else
return Error(Err, "Alias Collision on '" + SGA->getName()+
"': aliases have different aliasees");
} else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
if (!isa<GlobalVariable>(DAliasee))
return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
"': aliasee is not global variable");
NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
SGA->getName(), DAliaseeConst, Dest);
CopyGVAttributes(NewGA, SGA);
if (SGA->getType() != DGVar->getType())
DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
DGVar->getType()));
else
DGVar->replaceAllUsesWith(NewGA);
DGVar->eraseFromParent();
} else
return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
"': symbol multiple defined");
} else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
if (DF->isDeclaration() || DF->isWeakForLinker()) {
if (!isa<Function>(DAliasee))
return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
"': aliasee is not function");
NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
SGA->getName(), DAliaseeConst, Dest);
CopyGVAttributes(NewGA, SGA);
if (SGA->getType() != DF->getType())
DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
DF->getType()));
else
DF->replaceAllUsesWith(NewGA);
DF->eraseFromParent();
} else
return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
"': symbol multiple defined");
} else {
NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
SGA->getName(), DAliaseeConst, Dest);
CopyGVAttributes(NewGA, SGA);
}
assert(NewGA && "No alias was created in destination module!");
if (NewGA->getName() != SGA->getName() &&
!NewGA->hasLocalLinkage())
ForceRenaming(NewGA, SGA->getName());
ValueMap[SGA] = NewGA;
}
return false;
}
static bool LinkGlobalInits(Module *Dest, const Module *Src,
ValueToValueMapTy &ValueMap,
std::string *Err) {
for (Module::const_global_iterator I = Src->global_begin(),
E = Src->global_end(); I != E; ++I) {
const GlobalVariable *SGV = I;
if (SGV->hasInitializer()) { Constant *SInit =
cast<Constant>(MapValue(SGV->getInitializer(), ValueMap));
GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
if (DGVar->hasInitializer()) {
if (SGV->hasExternalLinkage()) {
if (DGVar->getInitializer() != SInit)
return Error(Err, "Global Variable Collision on '" +
SGV->getName() +
"': global variables have different initializers");
} else if (DGVar->isWeakForLinker()) {
} else if (SGV->isWeakForLinker()) {
} else if (DGVar->hasAppendingLinkage()) {
llvm_unreachable("Appending linkage unimplemented!");
} else {
llvm_unreachable("Unknown linkage!");
}
} else {
DGVar->setInitializer(SInit);
}
} else {
assert(SGV->isWeakForLinker());
}
}
}
return false;
}
static bool LinkFunctionProtos(Module *Dest, const Module *Src,
ValueToValueMapTy &ValueMap,
std::string *Err) {
ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
const Function *SF = I; GlobalValue *DGV = 0;
if (SF->hasName() && !SF->hasLocalLinkage())
DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
if (DGV && DGV->hasLocalLinkage())
DGV = 0;
if (DGV && DGV->getType() != SF->getType())
RecursiveResolveTypes(SF->getType(), DGV->getType());
GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
bool LinkFromSrc = false;
if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
return true;
if (DGV == 0) {
Function *NewDF = Function::Create(SF->getFunctionType(),
SF->getLinkage(),
SF->getName(), Dest);
CopyGVAttributes(NewDF, SF);
if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
ForceRenaming(NewDF, SF->getName());
ValueMap[SF] = NewDF;
continue;
}
if (DGV->isDeclaration())
DGV->setVisibility(SF->getVisibility());
if (LinkFromSrc) {
if (isa<GlobalAlias>(DGV))
return Error(Err, "Function-Alias Collision on '" + SF->getName() +
"': symbol multiple defined");
Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
SF->getName(), Dest);
CopyGVAttributes(NewDF, SF);
DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
DGV->getType()));
if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
Var->eraseFromParent();
else
cast<Function>(DGV)->eraseFromParent();
if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
ForceRenaming(NewDF, SF->getName());
ValueMap[SF] = NewDF;
continue;
}
if (isa<GlobalAlias>(DGV)) {
if (!SF->isDeclaration() && !SF->isWeakForLinker())
return Error(Err, "Function-Alias Collision on '" + SF->getName() +
"': symbol multiple defined");
}
DGV->setLinkage(NewLinkage);
ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
}
return false;
}
static bool LinkFunctionBody(Function *Dest, Function *Src,
ValueToValueMapTy &ValueMap,
std::string *Err) {
assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
Function::arg_iterator DI = Dest->arg_begin();
for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
I != E; ++I, ++DI) {
DI->setName(I->getName());
ValueMap[I] = DI;
}
Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries);
for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
I != E; ++I)
ValueMap.erase(I);
return false;
}
static bool LinkFunctionBodies(Module *Dest, Module *Src,
ValueToValueMapTy &ValueMap,
std::string *Err) {
for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
if (!SF->isDeclaration()) { Function *DF = dyn_cast<Function>(ValueMap[SF]);
if (DF && DF->isDeclaration())
if (LinkFunctionBody(DF, SF, ValueMap, Err))
return true;
}
}
return false;
}
static bool LinkAppendingVars(Module *M,
std::multimap<std::string, GlobalVariable *> &AppendingVars,
std::string *ErrorMsg) {
if (AppendingVars.empty()) return false;
std::vector<Constant*> Inits;
while (AppendingVars.size() > 1) {
std::multimap<std::string,
GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
if (First->first == Second->first) {
GlobalVariable *G1 = First->second, *G2 = Second->second;
const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
if (T1->getElementType() != T2->getElementType())
return Error(ErrorMsg,
"Appending variables with different element types need to be linked!");
if (G1->isConstant() != G2->isConstant())
return Error(ErrorMsg,
"Appending variables linked with different const'ness!");
if (G1->getAlignment() != G2->getAlignment())
return Error(ErrorMsg,
"Appending variables with different alignment need to be linked!");
if (G1->getVisibility() != G2->getVisibility())
return Error(ErrorMsg,
"Appending variables with different visibility need to be linked!");
if (G1->getSection() != G2->getSection())
return Error(ErrorMsg,
"Appending variables with different section name need to be linked!");
unsigned NewSize = T1->getNumElements() + T2->getNumElements();
ArrayType *NewType = ArrayType::get(T1->getElementType(),
NewSize);
G1->setName("");
GlobalVariable *NG =
new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
0, First->first, 0, G1->isThreadLocal(),
G1->getType()->getAddressSpace());
CopyGVAttributes(NG, G1);
Inits.reserve(NewSize);
if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Inits.push_back(I->getOperand(i));
} else {
assert(isa<ConstantAggregateZero>(G1->getInitializer()));
Constant *CV = Constant::getNullValue(T1->getElementType());
for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Inits.push_back(CV);
}
if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Inits.push_back(I->getOperand(i));
} else {
assert(isa<ConstantAggregateZero>(G2->getInitializer()));
Constant *CV = Constant::getNullValue(T2->getElementType());
for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Inits.push_back(CV);
}
NG->setInitializer(ConstantArray::get(NewType, Inits));
Inits.clear();
G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
G1->getType()));
G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
G2->getType()));
M->getGlobalList().erase(G1);
M->getGlobalList().erase(G2);
Second->second = NG;
}
AppendingVars.erase(First);
}
return false;
}
static bool ResolveAliases(Module *Dest) {
for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
I != E; ++I)
if (const Constant *C = I->getAliasee()) {
while (dyn_cast<GlobalAlias>(C))
C = cast<GlobalAlias>(C)->getAliasee();
const GlobalValue *GV = dyn_cast<GlobalValue>(C);
if (C != I && !(GV && GV->isDeclaration()))
I->replaceAllUsesWith(const_cast<Constant*>(C));
}
return false;
}
bool
Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
assert(Dest != 0 && "Invalid Destination module");
assert(Src != 0 && "Invalid Source Module");
if (Dest->getDataLayout().empty()) {
if (!Src->getDataLayout().empty()) {
Dest->setDataLayout(Src->getDataLayout());
} else {
std::string DataLayout;
if (Dest->getEndianness() == Module::AnyEndianness) {
if (Src->getEndianness() == Module::BigEndian)
DataLayout.append("E");
else if (Src->getEndianness() == Module::LittleEndian)
DataLayout.append("e");
}
if (Dest->getPointerSize() == Module::AnyPointerSize) {
if (Src->getPointerSize() == Module::Pointer64)
DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
else if (Src->getPointerSize() == Module::Pointer32)
DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
}
Dest->setDataLayout(DataLayout);
}
}
if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
Dest->setTargetTriple(Src->getTargetTriple());
if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
Src->getDataLayout() != Dest->getDataLayout())
errs() << "WARNING: Linking two modules of different data layouts!\n";
if (!Src->getTargetTriple().empty() &&
Dest->getTargetTriple() != Src->getTargetTriple()) {
errs() << "WARNING: Linking two modules of different target triples: ";
if (!Src->getModuleIdentifier().empty())
errs() << Src->getModuleIdentifier() << ": ";
errs() << "'" << Src->getTargetTriple() << "' and '"
<< Dest->getTargetTriple() << "'\n";
}
if (!Src->getModuleInlineAsm().empty()) {
if (Dest->getModuleInlineAsm().empty())
Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
else
Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
Src->getModuleInlineAsm());
}
for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
SI != SE; ++SI)
Dest->addLibrary(*SI);
if (LinkTypes(Dest, Src, ErrorMsg))
return true;
ValueToValueMapTy ValueMap;
std::multimap<std::string, GlobalVariable *> AppendingVars;
for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
I != E; ++I) {
if (I->hasAppendingLinkage())
AppendingVars.insert(std::make_pair(I->getName(), I));
}
if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
return true;
if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
return true;
if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
if (ResolveAliases(Dest)) return true;
LinkNamedMDNodes(Dest, Src, ValueMap);
const std::string &modId = Src->getModuleIdentifier();
if (!modId.empty())
Dest->removeLibrary(sys::path::stem(modId));
return false;
}