#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Constants.h"
+#include "llvm/IR/DiagnosticInfo.h"
+#include "llvm/IR/DiagnosticPrinter.h"
+#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/Support/CommandLine.h"
Value *materializeValueFor(Value *V) override;
};
+ namespace {
+ class LinkDiagnosticInfo : public DiagnosticInfo {
+ const Twine &Msg;
+
+ public:
+ LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
+ void print(DiagnosticPrinter &DP) const override;
+ };
+ LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
+ const Twine &Msg)
+ : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
+ void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
+ }
+
/// ModuleLinker - This is an implementation class for the LinkModules
/// function, which is the entrypoint for this file.
class ModuleLinker {
// Vector of functions to lazily link in.
std::vector<Function*> LazilyLinkFunctions;
- bool SuppressWarnings;
-
public:
- std::string ErrorMsg;
-
- ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
- bool SuppressWarnings=false)
+ ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
: DstM(dstM), SrcM(srcM), TypeMap(Set),
- ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
- SuppressWarnings(SuppressWarnings) {}
+ ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode) {}
bool run();
private:
- /// emitError - Helper method for setting a message and returning an error
- /// code.
+ bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
+ const GlobalValue &Src);
+
+ /// Helper method for setting a message and returning an error code.
bool emitError(const Twine &Message) {
- ErrorMsg = Message.str();
+ DstM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
return true;
}
+ void emitWarning(const Twine &Message) {
+ DstM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
+ }
+
bool getComdatLeader(Module *M, StringRef ComdatName,
const GlobalVariable *&GVar);
bool computeResultingSelectionKind(StringRef ComdatName,
LinkFromSrc);
}
-// FIXME: Duplicated from the gold plugin. This should be refactored somewhere.
-static bool isDeclaration(const GlobalValue &V) {
- if (V.hasAvailableExternallyLinkage())
- return true;
+bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
+ const GlobalValue &Dest,
+ const GlobalValue &Src) {
+ bool SrcIsDeclaration = Src.isDeclarationForLinker();
+ bool DestIsDeclaration = Dest.isDeclarationForLinker();
+
+ // FIXME: Make datalayout mandatory and just use getDataLayout().
+ DataLayout DL(Dest.getParent());
+
+ if (SrcIsDeclaration) {
+ // If Src is external or if both Src & Dest are external.. Just link the
+ // external globals, we aren't adding anything.
+ if (Src.hasDLLImportStorageClass()) {
+ // If one of GVs is marked as DLLImport, result should be dllimport'ed.
+ LinkFromSrc = DestIsDeclaration;
+ return false;
+ }
+ // If the Dest is weak, use the source linkage.
+ LinkFromSrc = Dest.hasExternalWeakLinkage();
+ return false;
+ }
+
+ if (DestIsDeclaration) {
+ // If Dest is external but Src is not:
+ LinkFromSrc = true;
+ return false;
+ }
+
+ if (Src.hasCommonLinkage()) {
+ if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
+ LinkFromSrc = true;
+ return false;
+ }
+
+ if (!Dest.hasCommonLinkage()) {
+ LinkFromSrc = false;
+ return false;
+ }
- if (V.isMaterializable())
+ uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
+ uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
+ LinkFromSrc = SrcSize > DestSize;
return false;
+ }
+
+ if (Src.isWeakForLinker()) {
+ assert(!Dest.hasExternalWeakLinkage());
+ assert(!Dest.hasAvailableExternallyLinkage());
+
+ if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
+ LinkFromSrc = true;
+ return false;
+ }
+
+ LinkFromSrc = false;
+ return false;
+ }
- return V.isDeclaration();
+ if (Dest.isWeakForLinker()) {
+ assert(Src.hasExternalLinkage());
+ LinkFromSrc = true;
+ return false;
+ }
+
+ assert(!Src.hasExternalWeakLinkage());
+ assert(!Dest.hasExternalWeakLinkage());
+ assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
+ "Unexpected linkage type!");
+ return emitError("Linking globals named '" + Src.getName() +
+ "': symbol multiply defined!");
}
/// This analyzes the two global values and determines what the result will look
assert(!Src->hasLocalLinkage() &&
"If Src has internal linkage, Dest shouldn't be set!");
- bool SrcIsDeclaration = isDeclaration(*Src);
- bool DestIsDeclaration = isDeclaration(*Dest);
+ if (shouldLinkFromSource(LinkFromSrc, *Dest, *Src))
+ return true;
- if (SrcIsDeclaration) {
- // If Src is external or if both Src & Dest are external.. Just link the
- // external globals, we aren't adding anything.
- if (Src->hasDLLImportStorageClass()) {
- // If one of GVs is marked as DLLImport, result should be dllimport'ed.
- if (DestIsDeclaration) {
- LinkFromSrc = true;
- LT = Src->getLinkage();
- }
- } else if (Dest->hasExternalWeakLinkage()) {
- // If the Dest is weak, use the source linkage.
- LinkFromSrc = true;
- LT = Src->getLinkage();
- } else {
- LinkFromSrc = false;
- LT = Dest->getLinkage();
- }
- } else if (DestIsDeclaration) {
- // If Dest is external but Src is not:
- LinkFromSrc = true;
+ if (LinkFromSrc)
LT = Src->getLinkage();
- } else if (Src->isWeakForLinker()) {
- assert(!Dest->hasExternalWeakLinkage());
- assert(!Dest->hasAvailableExternallyLinkage());
- if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
- ((Dest->hasLinkOnceLinkage() || Dest->hasWeakLinkage()) &&
- Src->hasCommonLinkage())) {
- LinkFromSrc = true;
- LT = Src->getLinkage();
- } else {
- LinkFromSrc = false;
- LT = Dest->getLinkage();
- }
- } else if (Dest->isWeakForLinker()) {
- assert(!Src->hasExternalWeakLinkage());
- LinkFromSrc = true;
- LT = GlobalValue::ExternalLinkage;
- } else {
- assert(!Src->hasExternalWeakLinkage());
- assert(!Dest->hasExternalWeakLinkage());
- assert(Dest->hasExternalLinkage() && Src->hasExternalLinkage() &&
- "Unexpected linkage type!");
- return emitError("Linking globals named '" + Src->getName() +
- "': symbol multiply defined!");
- }
+ else
+ LT = Dest->getLinkage();
// Compute the visibility. We follow the rules in the System V Application
// Binary Interface.
GlobalValue *DGV = getLinkedToGlobal(SGV);
llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
bool HasUnnamedAddr = SGV->hasUnnamedAddr();
+ unsigned Alignment = SGV->getAlignment();
bool LinkFromSrc = false;
Comdat *DC = nullptr;
return true;
NewVisibility = NV;
HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
+ if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
+ Alignment = std::max(Alignment, DGV->getAlignment());
+ else if (!LinkFromSrc)
+ Alignment = DGV->getAlignment();
// If we're not linking from the source, then keep the definition that we
// have.
if (!LinkFromSrc) {
// Special case for const propagation.
- if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
+ if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
+ DGVar->setAlignment(Alignment);
+
if (DGVar->isDeclaration() && SGV->isConstant() &&
!DGVar->isConstant())
DGVar->setConstant(true);
+ }
// Set calculated linkage, visibility and unnamed_addr.
DGV->setLinkage(NewLinkage);
SGV->getType()->getAddressSpace());
// Propagate alignment, visibility and section info.
copyGVAttributes(NewDGV, SGV);
+ NewDGV->setAlignment(Alignment);
if (NewVisibility)
NewDGV->setVisibility(*NewVisibility);
NewDGV->setUnnamedAddr(HasUnnamedAddr);
case Module::Warning: {
// Emit a warning if the values differ.
if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
- if (!SuppressWarnings) {
- errs() << "WARNING: linking module flags '" << ID->getString()
- << "': IDs have conflicting values";
- }
+ emitWarning("linking module flags '" + ID->getString() +
+ "': IDs have conflicting values");
}
continue;
}
if (SrcM->getDataLayout() && DstM->getDataLayout() &&
*SrcM->getDataLayout() != *DstM->getDataLayout()) {
- if (!SuppressWarnings) {
- errs() << "WARNING: Linking two modules of different data layouts: '"
- << SrcM->getModuleIdentifier() << "' is '"
- << SrcM->getDataLayoutStr() << "' whereas '"
- << DstM->getModuleIdentifier() << "' is '"
- << DstM->getDataLayoutStr() << "'\n";
- }
+ emitWarning("Linking two modules of different data layouts: '" +
+ SrcM->getModuleIdentifier() + "' is '" +
+ SrcM->getDataLayoutStr() + "' whereas '" +
+ DstM->getModuleIdentifier() + "' is '" +
+ DstM->getDataLayoutStr() + "'\n");
}
if (!SrcM->getTargetTriple().empty() &&
DstM->getTargetTriple() != SrcM->getTargetTriple()) {
- if (!SuppressWarnings) {
- errs() << "WARNING: Linking two modules of different target triples: "
- << SrcM->getModuleIdentifier() << "' is '"
- << SrcM->getTargetTriple() << "' whereas '"
- << DstM->getModuleIdentifier() << "' is '"
- << DstM->getTargetTriple() << "'\n";
- }
+ emitWarning("Linking two modules of different target triples: " +
+ SrcM->getModuleIdentifier() + "' is '" +
+ SrcM->getTargetTriple() + "' whereas '" +
+ DstM->getModuleIdentifier() + "' is '" +
+ DstM->getTargetTriple() + "'\n");
}
// Append the module inline asm string.
SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
}
- // Skip if no body (function is external) or materialize.
- if (SF->isDeclaration()) {
- if (!SF->isMaterializable())
- continue;
- if (SF->Materialize(&ErrorMsg))
- return true;
+ // Materialize if needed.
+ if (SF->isMaterializable()) {
+ if (std::error_code EC = SF->materialize())
+ return emitError(EC.message());
}
+ // Skip if no body (function is external).
+ if (SF->isDeclaration())
+ continue;
+
linkFunctionBody(DF, SF);
SF->Dematerialize();
}
&ValMaterializer));
}
- // Materialize if necessary.
- if (SF->isDeclaration()) {
- if (!SF->isMaterializable())
- continue;
- if (SF->Materialize(&ErrorMsg))
- return true;
+ // Materialize if needed.
+ if (SF->isMaterializable()) {
+ if (std::error_code EC = SF->materialize())
+ return emitError(EC.message());
}
+ // Skip if no body (function is external).
+ if (SF->isDeclaration())
+ continue;
+
// Erase from vector *before* the function body is linked - linkFunctionBody could
// invalidate I.
LazilyLinkFunctions.erase(I);
return false;
}
-Linker::Linker(Module *M, bool SuppressWarnings)
- : Composite(M), SuppressWarnings(SuppressWarnings) {
+Linker::Linker(Module *M) : Composite(M) {
TypeFinder StructTypes;
StructTypes.run(*M, true);
IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
Composite = nullptr;
}
-bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
- ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
- SuppressWarnings);
- if (TheLinker.run()) {
- if (ErrorMsg)
- *ErrorMsg = TheLinker.ErrorMsg;
- return true;
- }
- return false;
+bool Linker::linkInModule(Module *Src, unsigned Mode) {
+ ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
+ return TheLinker.run();
}
//===----------------------------------------------------------------------===//
/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
/// the problem. Upon failure, the Dest module could be in a modified state,
/// and shouldn't be relied on to be consistent.
-bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
- std::string *ErrorMsg) {
+bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode) {
Linker L(Dest);
- return L.linkInModule(Src, Mode, ErrorMsg);
+ return L.linkInModule(Src, Mode);
}
//===----------------------------------------------------------------------===//
// C API.
//===----------------------------------------------------------------------===//
+static void bindingDiagnosticHandler(const llvm::DiagnosticInfo &DI,
+ void *Context) {
+ if (DI.getSeverity() != DS_Error)
+ return;
+
+ std::string *Message = (std::string *)Context;
+ {
+ raw_string_ostream Stream(*Message);
+ DiagnosticPrinterRawOStream DP(Stream);
+ DI.print(DP);
+ }
+}
+
+
LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
LLVMLinkerMode Mode, char **OutMessages) {
- std::string Messages;
- LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
- Mode, OutMessages? &Messages : nullptr);
- if (OutMessages)
- *OutMessages = strdup(Messages.c_str());
+ Module *D = unwrap(Dest);
+ LLVMContext &Ctx = D->getContext();
+
+ LLVMContext::DiagnosticHandlerTy OldHandler = Ctx.getDiagnosticHandler();
+ void *OldDiagnosticContext = Ctx.getDiagnosticContext();
+ std::string Message;
+ Ctx.setDiagnosticHandler(bindingDiagnosticHandler, &Message);
+ LLVMBool Result = Linker::LinkModules(D, unwrap(Src), Mode);
+ Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext);
+
+ if (OutMessages && Result)
+ *OutMessages = strdup(Message.c_str());
return Result;
}