#include "llvm/Linker/IRMover.h"
#include "LinkDiagnosticInfo.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GVMaterializer.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PseudoProbe.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/Object/ModuleSymbolTable.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <utility>
using namespace llvm;
namespace {
class TypeMapTy : public ValueMapTypeRemapper {
DenseMap<Type *, Type *> MappedTypes;
SmallVector<Type *, 16> SpeculativeTypes;
SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
SmallVector<StructType *, 16> SrcDefinitionsToResolve;
SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
public:
TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
: DstStructTypesSet(DstStructTypesSet) {}
IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
void addTypeMapping(Type *DstTy, Type *SrcTy);
void linkDefinedTypeBodies();
Type *get(Type *SrcTy);
Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
FunctionType *get(FunctionType *T) {
return cast<FunctionType>(get((Type *)T));
}
private:
Type *remapType(Type *SrcTy) override { return get(SrcTy); }
bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
};
}
void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
assert(SpeculativeTypes.empty());
assert(SpeculativeDstOpaqueTypes.empty());
if (!areTypesIsomorphic(DstTy, SrcTy)) {
for (Type *Ty : SpeculativeTypes)
MappedTypes.erase(Ty);
SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
SpeculativeDstOpaqueTypes.size());
for (StructType *Ty : SpeculativeDstOpaqueTypes)
DstResolvedOpaqueTypes.erase(Ty);
} else {
for (Type *Ty : SpeculativeTypes)
if (auto *STy = dyn_cast<StructType>(Ty))
if (STy->hasName())
STy->setName("");
}
SpeculativeTypes.clear();
SpeculativeDstOpaqueTypes.clear();
}
bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
if (DstTy->getTypeID() != SrcTy->getTypeID())
return false;
Type *&Entry = MappedTypes[SrcTy];
if (Entry)
return Entry == DstTy;
if (DstTy == SrcTy) {
Entry = DstTy;
return true;
}
if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
if (SSTy->isOpaque()) {
Entry = DstTy;
SpeculativeTypes.push_back(SrcTy);
return true;
}
if (cast<StructType>(DstTy)->isOpaque()) {
if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
return false;
SrcDefinitionsToResolve.push_back(SSTy);
SpeculativeTypes.push_back(SrcTy);
SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Entry = DstTy;
return true;
}
}
if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
return false;
if (isa<IntegerType>(DstTy))
return false; if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
return false;
} else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
return false;
} else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
StructType *SSTy = cast<StructType>(SrcTy);
if (DSTy->isLiteral() != SSTy->isLiteral() ||
DSTy->isPacked() != SSTy->isPacked())
return false;
} else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
return false;
} else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
return false;
}
Entry = DstTy;
SpeculativeTypes.push_back(SrcTy);
for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
if (!areTypesIsomorphic(DstTy->getContainedType(I),
SrcTy->getContainedType(I)))
return false;
return true;
}
void TypeMapTy::linkDefinedTypeBodies() {
SmallVector<Type *, 16> Elements;
for (StructType *SrcSTy : SrcDefinitionsToResolve) {
StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
assert(DstSTy->isOpaque());
Elements.resize(SrcSTy->getNumElements());
for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Elements[I] = get(SrcSTy->getElementType(I));
DstSTy->setBody(Elements, SrcSTy->isPacked());
DstStructTypesSet.switchToNonOpaque(DstSTy);
}
SrcDefinitionsToResolve.clear();
DstResolvedOpaqueTypes.clear();
}
void TypeMapTy::finishType(StructType *DTy, StructType *STy,
ArrayRef<Type *> ETypes) {
DTy->setBody(ETypes, STy->isPacked());
if (STy->hasName()) {
SmallString<16> TmpName = STy->getName();
STy->setName("");
DTy->setName(TmpName);
}
DstStructTypesSet.addNonOpaque(DTy);
}
Type *TypeMapTy::get(Type *Ty) {
SmallPtrSet<StructType *, 8> Visited;
return get(Ty, Visited);
}
Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
Type **Entry = &MappedTypes[Ty];
if (*Entry)
return *Entry;
bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
if (!IsUniqued) {
#ifndef NDEBUG
for (auto &Pair : MappedTypes) {
assert(!(Pair.first != Ty && Pair.second == Ty) &&
"mapping to a source type");
}
#endif
if (!Visited.insert(cast<StructType>(Ty)).second) {
StructType *DTy = StructType::create(Ty->getContext());
return *Entry = DTy;
}
}
SmallVector<Type *, 4> ElementTypes;
if (Ty->getNumContainedTypes() == 0 && IsUniqued)
return *Entry = Ty;
bool AnyChange = false;
ElementTypes.resize(Ty->getNumContainedTypes());
for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
ElementTypes[I] = get(Ty->getContainedType(I), Visited);
AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
}
Entry = &MappedTypes[Ty];
if (*Entry) {
if (auto *DTy = dyn_cast<StructType>(*Entry)) {
if (DTy->isOpaque()) {
auto *STy = cast<StructType>(Ty);
finishType(DTy, STy, ElementTypes);
}
}
return *Entry;
}
if (!AnyChange && IsUniqued)
return *Entry = Ty;
switch (Ty->getTypeID()) {
default:
llvm_unreachable("unknown derived type to remap");
case Type::ArrayTyID:
return *Entry = ArrayType::get(ElementTypes[0],
cast<ArrayType>(Ty)->getNumElements());
case Type::ScalableVectorTyID:
case Type::FixedVectorTyID:
return *Entry = VectorType::get(ElementTypes[0],
cast<VectorType>(Ty)->getElementCount());
case Type::PointerTyID:
return *Entry = PointerType::get(ElementTypes[0],
cast<PointerType>(Ty)->getAddressSpace());
case Type::FunctionTyID:
return *Entry = FunctionType::get(ElementTypes[0],
makeArrayRef(ElementTypes).slice(1),
cast<FunctionType>(Ty)->isVarArg());
case Type::StructTyID: {
auto *STy = cast<StructType>(Ty);
bool IsPacked = STy->isPacked();
if (IsUniqued)
return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
if (STy->isOpaque()) {
DstStructTypesSet.addOpaque(STy);
return *Entry = Ty;
}
if (StructType *OldT =
DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
STy->setName("");
return *Entry = OldT;
}
if (!AnyChange) {
DstStructTypesSet.addNonOpaque(STy);
return *Entry = Ty;
}
StructType *DTy = StructType::create(Ty->getContext());
finishType(DTy, STy, ElementTypes);
return *Entry = DTy;
}
}
}
LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
const Twine &Msg)
: DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
namespace {
class IRLinker;
class GlobalValueMaterializer final : public ValueMaterializer {
IRLinker &TheIRLinker;
public:
GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Value *materialize(Value *V) override;
};
class LocalValueMaterializer final : public ValueMaterializer {
IRLinker &TheIRLinker;
public:
LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Value *materialize(Value *V) override;
};
typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
class IRLinker {
Module &DstM;
std::unique_ptr<Module> SrcM;
IRMover::LazyCallback AddLazyFor;
TypeMapTy TypeMap;
GlobalValueMaterializer GValMaterializer;
LocalValueMaterializer LValMaterializer;
MDMapT &SharedMDs;
ValueToValueMapTy ValueMap;
ValueToValueMapTy IndirectSymbolValueMap;
DenseSet<GlobalValue *> ValuesToLink;
std::vector<GlobalValue *> Worklist;
std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
void maybeAdd(GlobalValue *GV) {
if (ValuesToLink.insert(GV).second)
Worklist.push_back(GV);
}
bool IsPerformingImport;
bool DoneLinkingBodies = false;
Optional<Error> FoundError;
void setError(Error E) {
if (E)
FoundError = std::move(E);
}
Error stringErr(const Twine &T) {
return make_error<StringError>(T, inconvertibleErrorCode());
}
ValueMapper Mapper;
unsigned IndirectSymbolMCID;
GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
void emitWarning(const Twine &Message) {
SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
}
GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
return nullptr;
GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
if (!DGV)
return nullptr;
if (DGV->hasLocalLinkage())
return nullptr;
if (auto *FDGV = dyn_cast<Function>(DGV))
if (FDGV->isIntrinsic())
if (const auto *FSrcGV = dyn_cast<Function>(SrcGV))
if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
return nullptr;
return DGV;
}
void computeTypeMapping();
Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
const GlobalVariable *SrcGV);
bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
bool ForIndirectSymbol);
Error linkModuleFlagsMetadata();
void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
Error linkFunctionBody(Function &Dst, Function &Src);
void linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src);
void linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src);
Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
Function *copyFunctionProto(const Function *SF);
GlobalValue *copyIndirectSymbolProto(const GlobalValue *SGV);
void flushRAUWWorklist();
void prepareCompileUnitsForImport();
void linkNamedMDNodes();
public:
IRLinker(Module &DstM, MDMapT &SharedMDs,
IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
ArrayRef<GlobalValue *> ValuesToLink,
IRMover::LazyCallback AddLazyFor, bool IsPerformingImport)
: DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
Mapper(ValueMap, RF_ReuseAndMutateDistinctMDs | RF_IgnoreMissingLocals,
&TypeMap, &GValMaterializer),
IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
IndirectSymbolValueMap, &LValMaterializer)) {
ValueMap.getMDMap() = std::move(SharedMDs);
for (GlobalValue *GV : ValuesToLink)
maybeAdd(GV);
if (IsPerformingImport)
prepareCompileUnitsForImport();
}
~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Error run();
Value *materialize(Value *V, bool ForIndirectSymbol);
};
}
static void forceRenaming(GlobalValue *GV, StringRef Name) {
if (GV->hasLocalLinkage() || GV->getName() == Name)
return;
Module *M = GV->getParent();
if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
GV->takeName(ConflictGV);
ConflictGV->setName(Name); assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
} else {
GV->setName(Name); }
}
Value *GlobalValueMaterializer::materialize(Value *SGV) {
return TheIRLinker.materialize(SGV, false);
}
Value *LocalValueMaterializer::materialize(Value *SGV) {
return TheIRLinker.materialize(SGV, true);
}
Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
auto *SGV = dyn_cast<GlobalValue>(V);
if (!SGV)
return nullptr;
if (SGV->getParent() != &DstM && SGV->getParent() != SrcM.get())
return nullptr;
Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
if (!NewProto) {
setError(NewProto.takeError());
return nullptr;
}
if (!*NewProto)
return nullptr;
GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
if (!New)
return *NewProto;
if (auto *F = dyn_cast<Function>(New)) {
if (!F->isDeclaration())
return New;
} else if (auto *V = dyn_cast<GlobalVariable>(New)) {
if (V->hasInitializer() || V->hasAppendingLinkage())
return New;
} else if (auto *GA = dyn_cast<GlobalAlias>(New)) {
if (GA->getAliasee())
return New;
} else if (auto *GI = dyn_cast<GlobalIFunc>(New)) {
if (GI->getResolver())
return New;
} else {
llvm_unreachable("Invalid GlobalValue type");
}
if ((ForIndirectSymbol && ValueMap.lookup(SGV) == New) ||
(!ForIndirectSymbol && IndirectSymbolValueMap.lookup(SGV) == New))
return New;
if (ForIndirectSymbol || shouldLink(New, *SGV))
setError(linkGlobalValueBody(*New, *SGV));
return New;
}
GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
GlobalVariable *NewDGV =
new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
SGVar->isConstant(), GlobalValue::ExternalLinkage,
nullptr, SGVar->getName(),
nullptr, SGVar->getThreadLocalMode(),
SGVar->getAddressSpace());
NewDGV->setAlignment(SGVar->getAlign());
NewDGV->copyAttributesFrom(SGVar);
return NewDGV;
}
AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
for (int AttrIdx = Attribute::FirstTypeAttr;
AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
if (Attrs.hasAttributeAtIndex(i, TypedAttr)) {
if (Type *Ty =
Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
TypeMap.get(Ty));
break;
}
}
}
}
return Attrs;
}
Function *IRLinker::copyFunctionProto(const Function *SF) {
auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
GlobalValue::ExternalLinkage,
SF->getAddressSpace(), SF->getName(), &DstM);
F->copyAttributesFrom(SF);
F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
return F;
}
GlobalValue *IRLinker::copyIndirectSymbolProto(const GlobalValue *SGV) {
auto *Ty = TypeMap.get(SGV->getValueType());
if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
auto *DGA = GlobalAlias::create(Ty, SGV->getAddressSpace(),
GlobalValue::ExternalLinkage,
SGV->getName(), &DstM);
DGA->copyAttributesFrom(GA);
return DGA;
}
if (auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
auto *DGI = GlobalIFunc::create(Ty, SGV->getAddressSpace(),
GlobalValue::ExternalLinkage,
SGV->getName(), nullptr, &DstM);
DGI->copyAttributesFrom(GI);
return DGI;
}
llvm_unreachable("Invalid source global value type");
}
GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
bool ForDefinition) {
GlobalValue *NewGV;
if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
NewGV = copyGlobalVariableProto(SGVar);
} else if (auto *SF = dyn_cast<Function>(SGV)) {
NewGV = copyFunctionProto(SF);
} else {
if (ForDefinition)
NewGV = copyIndirectSymbolProto(SGV);
else if (SGV->getValueType()->isFunctionTy())
NewGV =
Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
GlobalValue::ExternalLinkage, SGV->getAddressSpace(),
SGV->getName(), &DstM);
else
NewGV =
new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
false, GlobalValue::ExternalLinkage,
nullptr, SGV->getName(),
nullptr,
SGV->getThreadLocalMode(), SGV->getAddressSpace());
}
if (ForDefinition)
NewGV->setLinkage(SGV->getLinkage());
else if (SGV->hasExternalWeakLinkage())
NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
}
if (auto *NewF = dyn_cast<Function>(NewGV)) {
NewF->setPersonalityFn(nullptr);
NewF->setPrefixData(nullptr);
NewF->setPrologueData(nullptr);
}
return NewGV;
}
static StringRef getTypeNamePrefix(StringRef Name) {
size_t DotPos = Name.rfind('.');
return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
!isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
? Name
: Name.substr(0, DotPos);
}
void IRLinker::computeTypeMapping() {
for (GlobalValue &SGV : SrcM->globals()) {
GlobalValue *DGV = getLinkedToGlobal(&SGV);
if (!DGV)
continue;
if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
continue;
}
ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
}
for (GlobalValue &SGV : *SrcM)
if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
if (DGV->getType() == SGV.getType()) {
continue;
}
TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
}
for (GlobalValue &SGV : SrcM->aliases())
if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
for (StructType *ST : Types) {
if (!ST->hasName())
continue;
if (TypeMap.DstStructTypesSet.hasType(ST)) {
continue;
}
auto STTypePrefix = getTypeNamePrefix(ST->getName());
if (STTypePrefix.size() == ST->getName().size())
continue;
StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
if (!DST)
continue;
if (TypeMap.DstStructTypesSet.hasType(DST))
TypeMap.addTypeMapping(DST, ST);
}
TypeMap.linkDefinedTypeBodies();
}
static void getArrayElements(const Constant *C,
SmallVectorImpl<Constant *> &Dest) {
unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
for (unsigned i = 0; i != NumElements; ++i)
Dest.push_back(C->getAggregateElement(i));
}
Expected<Constant *>
IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
const GlobalVariable *SrcGV) {
if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
return stringErr(
"Linking globals named '" + SrcGV->getName() +
"': can only link appending global with another appending "
"global!");
if (DstGV->isConstant() != SrcGV->isConstant())
return stringErr("Appending variables linked with different const'ness!");
if (DstGV->getAlign() != SrcGV->getAlign())
return stringErr(
"Appending variables with different alignment need to be linked!");
if (DstGV->getVisibility() != SrcGV->getVisibility())
return stringErr(
"Appending variables with different visibility need to be linked!");
if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
return stringErr(
"Appending variables with different unnamed_addr need to be linked!");
if (DstGV->getSection() != SrcGV->getSection())
return stringErr(
"Appending variables with different section name need to be linked!");
}
if (SrcGV->isDeclaration())
return DstGV;
Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
->getElementType();
StringRef Name = SrcGV->getName();
bool IsNewStructor = false;
bool IsOldStructor = false;
if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
if (cast<StructType>(EltTy)->getNumElements() == 3)
IsNewStructor = true;
else
IsOldStructor = true;
}
PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
if (IsOldStructor) {
auto &ST = *cast<StructType>(EltTy);
Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
EltTy = StructType::get(SrcGV->getContext(), Tys, false);
}
uint64_t DstNumElements = 0;
if (DstGV && !DstGV->isDeclaration()) {
ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
DstNumElements = DstTy->getNumElements();
if (EltTy != DstTy->getElementType())
return stringErr("Appending variables with different element types!");
}
SmallVector<Constant *, 16> SrcElements;
getArrayElements(SrcGV->getInitializer(), SrcElements);
if (IsNewStructor) {
erase_if(SrcElements, [this](Constant *E) {
auto *Key =
dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
if (!Key)
return false;
GlobalValue *DGV = getLinkedToGlobal(Key);
return !shouldLink(DGV, *Key);
});
}
uint64_t NewSize = DstNumElements + SrcElements.size();
ArrayType *NewType = ArrayType::get(EltTy, NewSize);
GlobalVariable *NG = new GlobalVariable(
DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
nullptr, "", DstGV, SrcGV->getThreadLocalMode(),
SrcGV->getAddressSpace());
NG->copyAttributesFrom(SrcGV);
forceRenaming(NG, SrcGV->getName());
Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Mapper.scheduleMapAppendingVariable(
*NG,
(DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
IsOldStructor, SrcElements);
if (DstGV) {
RAUWWorklist.push_back(
std::make_pair(DstGV, ConstantExpr::getBitCast(NG, DstGV->getType())));
}
return Ret;
}
bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
return true;
if (DGV && !DGV->isDeclarationForLinker())
return false;
if (SGV.isDeclaration() || DoneLinkingBodies)
return false;
bool LazilyAdded = false;
if (AddLazyFor)
AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
maybeAdd(&GV);
LazilyAdded = true;
});
return LazilyAdded;
}
Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
bool ForIndirectSymbol) {
GlobalValue *DGV = getLinkedToGlobal(SGV);
bool ShouldLink = shouldLink(DGV, *SGV);
if (ShouldLink) {
auto I = ValueMap.find(SGV);
if (I != ValueMap.end())
return cast<Constant>(I->second);
I = IndirectSymbolValueMap.find(SGV);
if (I != IndirectSymbolValueMap.end())
return cast<Constant>(I->second);
}
if (!ShouldLink && ForIndirectSymbol)
DGV = nullptr;
if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
cast<GlobalVariable>(SGV));
bool NeedsRenaming = false;
GlobalValue *NewGV;
if (DGV && !ShouldLink) {
NewGV = DGV;
} else {
if (DoneLinkingBodies)
return nullptr;
NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
if (ShouldLink || !ForIndirectSymbol)
NeedsRenaming = true;
}
if (Function *F = dyn_cast<Function>(NewGV))
if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
NewGV->eraseFromParent();
NewGV = *Remangled;
NeedsRenaming = false;
}
if (NeedsRenaming)
forceRenaming(NewGV, SGV->getName());
if (ShouldLink || ForIndirectSymbol) {
if (const Comdat *SC = SGV->getComdat()) {
if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
Comdat *DC = DstM.getOrInsertComdat(SC->getName());
DC->setSelectionKind(SC->getSelectionKind());
GO->setComdat(DC);
}
}
}
if (!ShouldLink && ForIndirectSymbol)
NewGV->setLinkage(GlobalValue::InternalLinkage);
Constant *C = NewGV;
if (DGV && NewGV != SGV) {
C = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
NewGV, TypeMap.get(SGV->getType()));
}
if (DGV && NewGV != DGV) {
RAUWWorklist.push_back(std::make_pair(
DGV,
ConstantExpr::getPointerBitCastOrAddrSpaceCast(NewGV, DGV->getType())));
}
return C;
}
void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
}
Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
assert(Dst.isDeclaration() && !Src.isDeclaration());
if (Error Err = Src.materialize())
return Err;
if (Src.hasPrefixData())
Dst.setPrefixData(Src.getPrefixData());
if (Src.hasPrologueData())
Dst.setPrologueData(Src.getPrologueData());
if (Src.hasPersonalityFn())
Dst.setPersonalityFn(Src.getPersonalityFn());
Dst.copyMetadata(&Src, 0);
Dst.stealArgumentListFrom(Src);
Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
Mapper.scheduleRemapFunction(Dst);
return Error::success();
}
void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
}
void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
}
Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
if (auto *F = dyn_cast<Function>(&Src))
return linkFunctionBody(cast<Function>(Dst), *F);
if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
return Error::success();
}
if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
return Error::success();
}
linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
return Error::success();
}
void IRLinker::flushRAUWWorklist() {
for (const auto &Elem : RAUWWorklist) {
GlobalValue *Old;
Value *New;
std::tie(Old, New) = Elem;
Old->replaceAllUsesWith(New);
Old->eraseFromParent();
}
RAUWWorklist.clear();
}
void IRLinker::prepareCompileUnitsForImport() {
NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
if (!SrcCompileUnits)
return;
for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) {
auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I));
assert(CU && "Expected valid compile unit");
CU->replaceEnumTypes(nullptr);
CU->replaceMacros(nullptr);
CU->replaceRetainedTypes(nullptr);
CU->replaceGlobalVariables(nullptr);
SmallVector<TrackingMDNodeRef, 4> AllImportedModules;
bool ReplaceImportedEntities = false;
for (auto *IE : CU->getImportedEntities()) {
DIScope *Scope = IE->getScope();
assert(Scope && "Invalid Scope encoding!");
if (isa<DILocalScope>(Scope))
AllImportedModules.emplace_back(IE);
else
ReplaceImportedEntities = true;
}
if (ReplaceImportedEntities) {
if (!AllImportedModules.empty())
CU->replaceImportedEntities(MDTuple::get(
CU->getContext(),
SmallVector<Metadata *, 16>(AllImportedModules.begin(),
AllImportedModules.end())));
else
CU->replaceImportedEntities(nullptr);
}
}
}
void IRLinker::linkNamedMDNodes() {
const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
for (const NamedMDNode &NMD : SrcM->named_metadata()) {
if (&NMD == SrcModFlags)
continue;
if (IsPerformingImport && NMD.getName() == PseudoProbeDescMetadataName) {
if (!DstM.getNamedMetadata(NMD.getName()))
emitWarning("Pseudo-probe ignored: source module '" +
SrcM->getModuleIdentifier() +
"' is compiled with -fpseudo-probe-for-profiling while "
"destination module '" +
DstM.getModuleIdentifier() + "' is not\n");
continue;
}
NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
for (const MDNode *Op : NMD.operands())
DestNMD->addOperand(Mapper.mapMDNode(*Op));
}
}
Error IRLinker::linkModuleFlagsMetadata() {
const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
if (!SrcModFlags)
return Error::success();
UpgradeModuleFlags(*SrcM);
NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
if (DstModFlags->getNumOperands() == 0) {
for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
DstModFlags->addOperand(SrcModFlags->getOperand(I));
return Error::success();
}
DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
SmallSetVector<MDNode *, 16> Requirements;
SmallVector<unsigned, 0> Mins;
DenseSet<MDString *> SeenMin;
for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
MDNode *Op = DstModFlags->getOperand(I);
uint64_t Behavior =
mdconst::extract<ConstantInt>(Op->getOperand(0))->getZExtValue();
MDString *ID = cast<MDString>(Op->getOperand(1));
if (Behavior == Module::Require) {
Requirements.insert(cast<MDNode>(Op->getOperand(2)));
} else {
if (Behavior == Module::Min)
Mins.push_back(I);
Flags[ID] = std::make_pair(Op, I);
}
}
for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
MDNode *SrcOp = SrcModFlags->getOperand(I);
ConstantInt *SrcBehavior =
mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
MDString *ID = cast<MDString>(SrcOp->getOperand(1));
MDNode *DstOp;
unsigned DstIndex;
std::tie(DstOp, DstIndex) = Flags.lookup(ID);
unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
SeenMin.insert(ID);
if (SrcBehaviorValue == Module::Require) {
if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
DstModFlags->addOperand(SrcOp);
}
continue;
}
if (!DstOp) {
if (SrcBehaviorValue == Module::Min) {
Mins.push_back(DstModFlags->getNumOperands());
SeenMin.erase(ID);
}
Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
DstModFlags->addOperand(SrcOp);
continue;
}
ConstantInt *DstBehavior =
mdconst::extract<ConstantInt>(DstOp->getOperand(0));
unsigned DstBehaviorValue = DstBehavior->getZExtValue();
auto overrideDstValue = [&]() {
DstModFlags->setOperand(DstIndex, SrcOp);
Flags[ID].first = SrcOp;
};
if (DstBehaviorValue == Module::Override) {
if (SrcBehaviorValue == Module::Override &&
SrcOp->getOperand(2) != DstOp->getOperand(2))
return stringErr("linking module flags '" + ID->getString() +
"': IDs have conflicting override values in '" +
SrcM->getModuleIdentifier() + "' and '" +
DstM.getModuleIdentifier() + "'");
continue;
} else if (SrcBehaviorValue == Module::Override) {
overrideDstValue();
continue;
}
if (SrcBehaviorValue != DstBehaviorValue) {
bool MinAndWarn = (SrcBehaviorValue == Module::Min &&
DstBehaviorValue == Module::Warning) ||
(DstBehaviorValue == Module::Min &&
SrcBehaviorValue == Module::Warning);
bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
DstBehaviorValue == Module::Warning) ||
(DstBehaviorValue == Module::Max &&
SrcBehaviorValue == Module::Warning);
if (!(MaxAndWarn || MinAndWarn))
return stringErr("linking module flags '" + ID->getString() +
"': IDs have conflicting behaviors in '" +
SrcM->getModuleIdentifier() + "' and '" +
DstM.getModuleIdentifier() + "'");
}
auto ensureDistinctOp = [&](MDNode *DstValue) {
assert(isa<MDTuple>(DstValue) &&
"Expected MDTuple when appending module flags");
if (DstValue->isDistinct())
return dyn_cast<MDTuple>(DstValue);
ArrayRef<MDOperand> DstOperands = DstValue->operands();
MDTuple *New = MDTuple::getDistinct(
DstM.getContext(),
SmallVector<Metadata *, 4>(DstOperands.begin(), DstOperands.end()));
Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
MDNode *Flag = MDTuple::getDistinct(DstM.getContext(), FlagOps);
DstModFlags->setOperand(DstIndex, Flag);
Flags[ID].first = Flag;
return New;
};
if ((DstBehaviorValue == Module::Warning ||
SrcBehaviorValue == Module::Warning) &&
SrcOp->getOperand(2) != DstOp->getOperand(2)) {
std::string Str;
raw_string_ostream(Str)
<< "linking module flags '" << ID->getString()
<< "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
<< "' from " << SrcM->getModuleIdentifier() << " with '"
<< *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
<< ')';
emitWarning(Str);
}
if (DstBehaviorValue == Module::Min || SrcBehaviorValue == Module::Min) {
ConstantInt *DstValue =
mdconst::extract<ConstantInt>(DstOp->getOperand(2));
ConstantInt *SrcValue =
mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
Metadata *FlagOps[] = {
(DstBehaviorValue != Module::Min ? SrcOp : DstOp)->getOperand(0), ID,
(SrcValue->getZExtValue() < DstValue->getZExtValue() ? SrcOp : DstOp)
->getOperand(2)};
MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
DstModFlags->setOperand(DstIndex, Flag);
Flags[ID].first = Flag;
continue;
}
if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
ConstantInt *DstValue =
mdconst::extract<ConstantInt>(DstOp->getOperand(2));
ConstantInt *SrcValue =
mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
Metadata *FlagOps[] = {
(DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
(SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
->getOperand(2)};
MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
DstModFlags->setOperand(DstIndex, Flag);
Flags[ID].first = Flag;
continue;
}
switch (SrcBehaviorValue) {
case Module::Require:
case Module::Override:
llvm_unreachable("not possible");
case Module::Error: {
if (SrcOp->getOperand(2) != DstOp->getOperand(2))
return stringErr("linking module flags '" + ID->getString() +
"': IDs have conflicting values in '" +
SrcM->getModuleIdentifier() + "' and '" +
DstM.getModuleIdentifier() + "'");
continue;
}
case Module::Warning: {
break;
}
case Module::Max: {
break;
}
case Module::Append: {
MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
for (const auto &O : SrcValue->operands())
DstValue->push_back(O);
break;
}
case Module::AppendUnique: {
SmallSetVector<Metadata *, 16> Elts;
MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Elts.insert(DstValue->op_begin(), DstValue->op_end());
Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
for (auto I = DstValue->getNumOperands(); I < Elts.size(); I++)
DstValue->push_back(Elts[I]);
break;
}
}
}
for (auto Idx : Mins) {
MDNode *Op = DstModFlags->getOperand(Idx);
MDString *ID = cast<MDString>(Op->getOperand(1));
if (!SeenMin.count(ID)) {
ConstantInt *V = mdconst::extract<ConstantInt>(Op->getOperand(2));
Metadata *FlagOps[] = {
Op->getOperand(0), ID,
ConstantAsMetadata::get(ConstantInt::get(V->getType(), 0))};
DstModFlags->setOperand(Idx, MDNode::get(DstM.getContext(), FlagOps));
}
}
for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
MDNode *Requirement = Requirements[I];
MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Metadata *ReqValue = Requirement->getOperand(1);
MDNode *Op = Flags[Flag].first;
if (!Op || Op->getOperand(2) != ReqValue)
return stringErr("linking module flags '" + Flag->getString() +
"': does not have the required value");
}
return Error::success();
}
static std::string adjustInlineAsm(const std::string &InlineAsm,
const Triple &Triple) {
if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
return ".text\n.balign 2\n.thumb\n" + InlineAsm;
if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
return ".text\n.balign 4\n.arm\n" + InlineAsm;
return InlineAsm;
}
Error IRLinker::run() {
if (SrcM->getMaterializer())
if (Error Err = SrcM->getMaterializer()->materializeMetadata())
return Err;
if (DstM.getDataLayout().isDefault())
DstM.setDataLayout(SrcM->getDataLayout());
if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
DstM.setTargetTriple(SrcM->getTargetTriple());
Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
bool EnableDLWarning = true;
bool EnableTripleWarning = true;
if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
std::string ModuleId = SrcM->getModuleIdentifier();
StringRef FileName = llvm::sys::path::filename(ModuleId);
bool SrcIsLibDevice =
FileName.startswith("libdevice") && FileName.endswith(".10.bc");
bool SrcHasLibDeviceDL =
(SrcM->getDataLayoutStr().empty() ||
SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
SrcTriple.getOSName() == "gpulibs") ||
(SrcTriple.getVendorName() == "unknown" &&
SrcTriple.getOSName() == "unknown");
EnableTripleWarning = !(SrcIsLibDevice && SrcHasLibDeviceTriple);
EnableDLWarning = !(SrcIsLibDevice && SrcHasLibDeviceDL);
}
if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
emitWarning("Linking two modules of different data layouts: '" +
SrcM->getModuleIdentifier() + "' is '" +
SrcM->getDataLayoutStr() + "' whereas '" +
DstM.getModuleIdentifier() + "' is '" +
DstM.getDataLayoutStr() + "'\n");
}
if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
!SrcTriple.isCompatibleWith(DstTriple))
emitWarning("Linking two modules of different target triples: '" +
SrcM->getModuleIdentifier() + "' is '" +
SrcM->getTargetTriple() + "' whereas '" +
DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
"'\n");
DstM.setTargetTriple(SrcTriple.merge(DstTriple));
computeTypeMapping();
std::reverse(Worklist.begin(), Worklist.end());
while (!Worklist.empty()) {
GlobalValue *GV = Worklist.back();
Worklist.pop_back();
if (ValueMap.find(GV) != ValueMap.end() ||
IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
continue;
assert(!GV->isDeclaration());
Mapper.mapValue(*GV);
if (FoundError)
return std::move(*FoundError);
flushRAUWWorklist();
}
DoneLinkingBodies = true;
Mapper.addFlags(RF_NullMapMissingGlobalValues);
linkNamedMDNodes();
if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
SrcTriple));
} else if (IsPerformingImport) {
ModuleSymbolTable::CollectAsmSymvers(*SrcM,
[&](StringRef Name, StringRef Alias) {
if (DstM.getNamedValue(Name)) {
SmallString<256> S(".symver ");
S += Name;
S += ", ";
S += Alias;
DstM.appendModuleInlineAsm(S);
}
});
}
Module::GlobalListType &Globals = DstM.getGlobalList();
for (GlobalVariable &GV : SrcM->globals()) {
if (GV.hasAppendingLinkage())
continue;
Value *NewValue = Mapper.mapValue(GV);
if (NewValue) {
auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
if (NewGV)
Globals.splice(Globals.end(), Globals, NewGV->getIterator());
}
}
return linkModuleFlagsMetadata();
}
IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
: ETypes(E), IsPacked(P) {}
IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
: ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
return IsPacked == That.IsPacked && ETypes == That.ETypes;
}
bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
return !this->operator==(That);
}
StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
return DenseMapInfo<StructType *>::getEmptyKey();
}
StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
return DenseMapInfo<StructType *>::getTombstoneKey();
}
unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
Key.IsPacked);
}
unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
return getHashValue(KeyTy(ST));
}
bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
const StructType *RHS) {
if (RHS == getEmptyKey() || RHS == getTombstoneKey())
return false;
return LHS == KeyTy(RHS);
}
bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
const StructType *RHS) {
if (RHS == getEmptyKey() || RHS == getTombstoneKey())
return LHS == RHS;
return KeyTy(LHS) == KeyTy(RHS);
}
void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
assert(!Ty->isOpaque());
NonOpaqueStructTypes.insert(Ty);
}
void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
assert(!Ty->isOpaque());
NonOpaqueStructTypes.insert(Ty);
bool Removed = OpaqueStructTypes.erase(Ty);
(void)Removed;
assert(Removed);
}
void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
assert(Ty->isOpaque());
OpaqueStructTypes.insert(Ty);
}
StructType *
IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
bool IsPacked) {
IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
auto I = NonOpaqueStructTypes.find_as(Key);
return I == NonOpaqueStructTypes.end() ? nullptr : *I;
}
bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
if (Ty->isOpaque())
return OpaqueStructTypes.count(Ty);
auto I = NonOpaqueStructTypes.find(Ty);
return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
}
IRMover::IRMover(Module &M) : Composite(M) {
TypeFinder StructTypes;
StructTypes.run(M, false);
for (StructType *Ty : StructTypes) {
if (Ty->isOpaque())
IdentifiedStructTypes.addOpaque(Ty);
else
IdentifiedStructTypes.addNonOpaque(Ty);
}
for (auto *MD : StructTypes.getVisitedMetadata()) {
SharedMDs[MD].reset(const_cast<MDNode *>(MD));
}
}
Error IRMover::move(std::unique_ptr<Module> Src,
ArrayRef<GlobalValue *> ValuesToLink,
LazyCallback AddLazyFor, bool IsPerformingImport) {
IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
std::move(Src), ValuesToLink, std::move(AddLazyFor),
IsPerformingImport);
Error E = TheIRLinker.run();
Composite.dropTriviallyDeadConstantArrays();
return E;
}