#include "llvm/Transforms/IPO/FunctionImport.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSummaryIndex.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/InitializePasses.h"
#include "llvm/Linker/IRMover.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO/Internalize.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <cassert>
#include <memory>
#include <set>
#include <string>
#include <system_error>
#include <tuple>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "function-import"
STATISTIC(NumImportedFunctionsThinLink,
"Number of functions thin link decided to import");
STATISTIC(NumImportedHotFunctionsThinLink,
"Number of hot functions thin link decided to import");
STATISTIC(NumImportedCriticalFunctionsThinLink,
"Number of critical functions thin link decided to import");
STATISTIC(NumImportedGlobalVarsThinLink,
"Number of global variables thin link decided to import");
STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
STATISTIC(NumImportedGlobalVars,
"Number of global variables imported in backend");
STATISTIC(NumImportedModules, "Number of modules imported from");
STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
STATISTIC(NumLiveSymbols, "Number of live symbols in index");
static cl::opt<unsigned> ImportInstrLimit(
"import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
cl::desc("Only import functions with less than N instructions"));
static cl::opt<int> ImportCutoff(
"import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
cl::desc("Only import first N functions if N>=0 (default -1)"));
static cl::opt<bool>
ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
cl::desc("Import functions with noinline attribute"));
static cl::opt<float>
ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
cl::Hidden, cl::value_desc("x"),
cl::desc("As we import functions, multiply the "
"`import-instr-limit` threshold by this factor "
"before processing newly imported functions"));
static cl::opt<float> ImportHotInstrFactor(
"import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
cl::value_desc("x"),
cl::desc("As we import functions called from hot callsite, multiply the "
"`import-instr-limit` threshold by this factor "
"before processing newly imported functions"));
static cl::opt<float> ImportHotMultiplier(
"import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
static cl::opt<float> ImportCriticalMultiplier(
"import-critical-multiplier", cl::init(100.0), cl::Hidden,
cl::value_desc("x"),
cl::desc(
"Multiply the `import-instr-limit` threshold for critical callsites"));
static cl::opt<float> ImportColdMultiplier(
"import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
cl::desc("Print imported functions"));
static cl::opt<bool> PrintImportFailures(
"print-import-failures", cl::init(false), cl::Hidden,
cl::desc("Print information for functions rejected for importing"));
static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
cl::desc("Compute dead symbols"));
static cl::opt<bool> EnableImportMetadata(
"enable-import-metadata", cl::init(false), cl::Hidden,
cl::desc("Enable import metadata like 'thinlto_src_module'"));
static cl::opt<std::string>
SummaryFile("summary-file",
cl::desc("The summary file to use for function importing."));
static cl::opt<bool>
ImportAllIndex("import-all-index",
cl::desc("Import all external functions in index."));
static std::unique_ptr<Module> loadFile(const std::string &FileName,
LLVMContext &Context) {
SMDiagnostic Err;
LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
std::unique_ptr<Module> Result =
getLazyIRFileModule(FileName, Err, Context,
true);
if (!Result) {
Err.print("function-import", errs());
report_fatal_error("Abort");
}
return Result;
}
static const GlobalValueSummary *
selectCallee(const ModuleSummaryIndex &Index,
ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
unsigned Threshold, StringRef CallerModulePath,
FunctionImporter::ImportFailureReason &Reason,
GlobalValue::GUID GUID) {
Reason = FunctionImporter::ImportFailureReason::None;
auto It = llvm::find_if(
CalleeSummaryList,
[&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
auto *GVSummary = SummaryPtr.get();
if (!Index.isGlobalValueLive(GVSummary)) {
Reason = FunctionImporter::ImportFailureReason::NotLive;
return false;
}
if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
return false;
}
auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
CalleeSummaryList.size() > 1 &&
Summary->modulePath() != CallerModulePath) {
Reason =
FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
return false;
}
if ((Summary->instCount() > Threshold) &&
!Summary->fflags().AlwaysInline && !ForceImportAll) {
Reason = FunctionImporter::ImportFailureReason::TooLarge;
return false;
}
if (Summary->notEligibleToImport()) {
Reason = FunctionImporter::ImportFailureReason::NotEligible;
return false;
}
if (Summary->fflags().NoInline && !ForceImportAll) {
Reason = FunctionImporter::ImportFailureReason::NoInline;
return false;
}
return true;
});
if (It == CalleeSummaryList.end())
return nullptr;
return cast<GlobalValueSummary>(It->get());
}
namespace {
using EdgeInfo =
std::tuple<const GlobalValueSummary *, unsigned >;
}
static bool shouldImportGlobal(const ValueInfo &VI,
const GVSummaryMapTy &DefinedGVSummaries) {
const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
if (GVS == DefinedGVSummaries.end())
return true;
if (VI.getSummaryList().size() > 1 &&
GlobalValue::isInterposableLinkage(GVS->second->linkage()))
return true;
return false;
}
static void computeImportForReferencedGlobals(
const GlobalValueSummary &Summary, const ModuleSummaryIndex &Index,
const GVSummaryMapTy &DefinedGVSummaries,
SmallVectorImpl<EdgeInfo> &Worklist,
FunctionImporter::ImportMapTy &ImportList,
StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
for (auto &VI : Summary.refs()) {
if (!shouldImportGlobal(VI, DefinedGVSummaries)) {
LLVM_DEBUG(
dbgs() << "Ref ignored! Target already in destination module.\n");
continue;
}
LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
RefSummary->modulePath() != Summary.modulePath();
};
for (auto &RefSummary : VI.getSummaryList())
if (isa<GlobalVarSummary>(RefSummary.get()) &&
Index.canImportGlobalVar(RefSummary.get(), true) &&
!LocalNotInModule(RefSummary.get())) {
auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
if (!ILI.second)
break;
NumImportedGlobalVarsThinLink++;
if (ExportLists)
(*ExportLists)[RefSummary->modulePath()].insert(VI);
if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get())))
Worklist.emplace_back(RefSummary.get(), 0);
break;
}
}
}
static const char *
getFailureName(FunctionImporter::ImportFailureReason Reason) {
switch (Reason) {
case FunctionImporter::ImportFailureReason::None:
return "None";
case FunctionImporter::ImportFailureReason::GlobalVar:
return "GlobalVar";
case FunctionImporter::ImportFailureReason::NotLive:
return "NotLive";
case FunctionImporter::ImportFailureReason::TooLarge:
return "TooLarge";
case FunctionImporter::ImportFailureReason::InterposableLinkage:
return "InterposableLinkage";
case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
return "LocalLinkageNotInModule";
case FunctionImporter::ImportFailureReason::NotEligible:
return "NotEligible";
case FunctionImporter::ImportFailureReason::NoInline:
return "NoInline";
}
llvm_unreachable("invalid reason");
}
static void computeImportForFunction(
const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
SmallVectorImpl<EdgeInfo> &Worklist,
FunctionImporter::ImportMapTy &ImportList,
StringMap<FunctionImporter::ExportSetTy> *ExportLists,
FunctionImporter::ImportThresholdsTy &ImportThresholds) {
computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries,
Worklist, ImportList, ExportLists);
static int ImportCount = 0;
for (auto &Edge : Summary.calls()) {
ValueInfo VI = Edge.first;
LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
<< "\n");
if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
<< " reached.\n");
continue;
}
if (DefinedGVSummaries.count(VI.getGUID())) {
LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
continue;
}
auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
if (Hotness == CalleeInfo::HotnessType::Hot)
return ImportHotMultiplier;
if (Hotness == CalleeInfo::HotnessType::Cold)
return ImportColdMultiplier;
if (Hotness == CalleeInfo::HotnessType::Critical)
return ImportCriticalMultiplier;
return 1.0;
};
const auto NewThreshold =
Threshold * GetBonusMultiplier(Edge.second.getHotness());
auto IT = ImportThresholds.insert(std::make_pair(
VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
bool PreviouslyVisited = !IT.second;
auto &ProcessedThreshold = std::get<0>(IT.first->second);
auto &CalleeSummary = std::get<1>(IT.first->second);
auto &FailureInfo = std::get<2>(IT.first->second);
bool IsHotCallsite =
Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
bool IsCriticalCallsite =
Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
const FunctionSummary *ResolvedCalleeSummary = nullptr;
if (CalleeSummary) {
assert(PreviouslyVisited);
if (NewThreshold <= ProcessedThreshold) {
LLVM_DEBUG(
dbgs() << "ignored! Target was already imported with Threshold "
<< ProcessedThreshold << "\n");
continue;
}
ProcessedThreshold = NewThreshold;
ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
} else {
if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
LLVM_DEBUG(
dbgs() << "ignored! Target was already rejected with Threshold "
<< ProcessedThreshold << "\n");
if (PrintImportFailures) {
assert(FailureInfo &&
"Expected FailureInfo for previously rejected candidate");
FailureInfo->Attempts++;
}
continue;
}
FunctionImporter::ImportFailureReason Reason;
CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
Summary.modulePath(), Reason, VI.getGUID());
if (!CalleeSummary) {
if (PreviouslyVisited) {
ProcessedThreshold = NewThreshold;
if (PrintImportFailures) {
assert(FailureInfo &&
"Expected FailureInfo for previously rejected candidate");
FailureInfo->Reason = Reason;
FailureInfo->Attempts++;
FailureInfo->MaxHotness =
std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
}
} else if (PrintImportFailures) {
assert(!FailureInfo &&
"Expected no FailureInfo for newly rejected candidate");
FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
VI, Edge.second.getHotness(), Reason, 1);
}
if (ForceImportAll) {
std::string Msg = std::string("Failed to import function ") +
VI.name().str() + " due to " +
getFailureName(Reason);
auto Error = make_error<StringError>(
Msg, make_error_code(errc::not_supported));
logAllUnhandledErrors(std::move(Error), errs(),
"Error importing module: ");
break;
} else {
LLVM_DEBUG(dbgs()
<< "ignored! No qualifying callee with summary found.\n");
continue;
}
}
CalleeSummary = CalleeSummary->getBaseObject();
ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
(ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
"selectCallee() didn't honor the threshold");
auto ExportModulePath = ResolvedCalleeSummary->modulePath();
auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
bool PreviouslyImported = !ILI.second;
if (!PreviouslyImported) {
NumImportedFunctionsThinLink++;
if (IsHotCallsite)
NumImportedHotFunctionsThinLink++;
if (IsCriticalCallsite)
NumImportedCriticalFunctionsThinLink++;
}
if (ExportLists)
(*ExportLists)[ExportModulePath].insert(VI);
}
auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
if (IsHotCallsite)
return Threshold * ImportHotInstrFactor;
return Threshold * ImportInstrFactor;
};
const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
ImportCount++;
Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
}
}
static void ComputeImportForModule(
const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
SmallVector<EdgeInfo, 128> Worklist;
FunctionImporter::ImportThresholdsTy ImportThresholds;
for (auto &GVSummary : DefinedGVSummaries) {
#ifndef NDEBUG
auto VI = Index.getValueInfo(GVSummary.first);
#endif
if (!Index.isGlobalValueLive(GVSummary.second)) {
LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
continue;
}
auto *FuncSummary =
dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
if (!FuncSummary)
continue;
LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
DefinedGVSummaries, Worklist, ImportList,
ExportLists, ImportThresholds);
}
while (!Worklist.empty()) {
auto GVInfo = Worklist.pop_back_val();
auto *Summary = std::get<0>(GVInfo);
auto Threshold = std::get<1>(GVInfo);
if (auto *FS = dyn_cast<FunctionSummary>(Summary))
computeImportForFunction(*FS, Index, Threshold, DefinedGVSummaries,
Worklist, ImportList, ExportLists,
ImportThresholds);
else
computeImportForReferencedGlobals(*Summary, Index, DefinedGVSummaries,
Worklist, ImportList, ExportLists);
}
if (PrintImportFailures) {
dbgs() << "Missed imports into module " << ModName << "\n";
for (auto &I : ImportThresholds) {
auto &ProcessedThreshold = std::get<0>(I.second);
auto &CalleeSummary = std::get<1>(I.second);
auto &FailureInfo = std::get<2>(I.second);
if (CalleeSummary)
continue; assert(FailureInfo);
FunctionSummary *FS = nullptr;
if (!FailureInfo->VI.getSummaryList().empty())
FS = dyn_cast<FunctionSummary>(
FailureInfo->VI.getSummaryList()[0]->getBaseObject());
dbgs() << FailureInfo->VI
<< ": Reason = " << getFailureName(FailureInfo->Reason)
<< ", Threshold = " << ProcessedThreshold
<< ", Size = " << (FS ? (int)FS->instCount() : -1)
<< ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
<< ", Attempts = " << FailureInfo->Attempts << "\n";
}
}
}
#ifndef NDEBUG
static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
auto SL = VI.getSummaryList();
return SL.empty()
? false
: SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
}
static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
GlobalValue::GUID G) {
if (const auto &VI = Index.getValueInfo(G))
return isGlobalVarSummary(Index, VI);
return false;
}
template <class T>
static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
T &Cont) {
unsigned NumGVS = 0;
for (auto &V : Cont)
if (isGlobalVarSummary(Index, V))
++NumGVS;
return NumGVS;
}
#endif
#ifndef NDEBUG
static bool
checkVariableImport(const ModuleSummaryIndex &Index,
StringMap<FunctionImporter::ImportMapTy> &ImportLists,
StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
DenseSet<GlobalValue::GUID> FlattenedImports;
for (auto &ImportPerModule : ImportLists)
for (auto &ExportPerModule : ImportPerModule.second)
FlattenedImports.insert(ExportPerModule.second.begin(),
ExportPerModule.second.end());
auto IsReadOrWriteOnlyVar = [&](StringRef ModulePath, const ValueInfo &VI) {
auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
Index.findSummaryInModule(VI, ModulePath));
return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS));
};
for (auto &ExportPerModule : ExportLists)
for (auto &VI : ExportPerModule.second)
if (!FlattenedImports.count(VI.getGUID()) &&
IsReadOrWriteOnlyVar(ExportPerModule.first(), VI))
return false;
return true;
}
#endif
void llvm::ComputeCrossModuleImport(
const ModuleSummaryIndex &Index,
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
StringMap<FunctionImporter::ImportMapTy> &ImportLists,
StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
auto &ImportList = ImportLists[DefinedGVSummaries.first()];
LLVM_DEBUG(dbgs() << "Computing import for Module '"
<< DefinedGVSummaries.first() << "'\n");
ComputeImportForModule(DefinedGVSummaries.second, Index,
DefinedGVSummaries.first(), ImportList,
&ExportLists);
}
for (auto &ELI : ExportLists) {
FunctionImporter::ExportSetTy NewExports;
const auto &DefinedGVSummaries =
ModuleToDefinedGVSummaries.lookup(ELI.first());
for (auto &EI : ELI.second) {
auto DS = DefinedGVSummaries.find(EI.getGUID());
assert(DS != DefinedGVSummaries.end());
auto *S = DS->getSecond();
S = S->getBaseObject();
if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
if (!Index.isWriteOnly(GVS))
for (const auto &VI : GVS->refs())
NewExports.insert(VI);
} else {
auto *FS = cast<FunctionSummary>(S);
for (auto &Edge : FS->calls())
NewExports.insert(Edge.first);
for (auto &Ref : FS->refs())
NewExports.insert(Ref);
}
}
for (auto EI = NewExports.begin(); EI != NewExports.end();) {
if (!DefinedGVSummaries.count(EI->getGUID()))
NewExports.erase(EI++);
else
++EI;
}
ELI.second.insert(NewExports.begin(), NewExports.end());
}
assert(checkVariableImport(Index, ImportLists, ExportLists));
#ifndef NDEBUG
LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
<< " modules:\n");
for (auto &ModuleImports : ImportLists) {
auto ModName = ModuleImports.first();
auto &Exports = ExportLists[ModName];
unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
<< Exports.size() - NumGVS << " functions and " << NumGVS
<< " vars. Imports from " << ModuleImports.second.size()
<< " modules.\n");
for (auto &Src : ModuleImports.second) {
auto SrcModName = Src.first();
unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
<< " functions imported from " << SrcModName << "\n");
LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
<< " global vars imported from " << SrcModName << "\n");
}
}
#endif
}
#ifndef NDEBUG
static void dumpImportListForModule(const ModuleSummaryIndex &Index,
StringRef ModulePath,
FunctionImporter::ImportMapTy &ImportList) {
LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
<< ImportList.size() << " modules.\n");
for (auto &Src : ImportList) {
auto SrcModName = Src.first();
unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
<< " functions imported from " << SrcModName << "\n");
LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
<< SrcModName << "\n");
}
}
#endif
void llvm::ComputeCrossModuleImportForModule(
StringRef ModulePath, const ModuleSummaryIndex &Index,
FunctionImporter::ImportMapTy &ImportList) {
GVSummaryMapTy FunctionSummaryMap;
Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
#ifndef NDEBUG
dumpImportListForModule(Index, ModulePath, ImportList);
#endif
}
void llvm::ComputeCrossModuleImportForModuleFromIndex(
StringRef ModulePath, const ModuleSummaryIndex &Index,
FunctionImporter::ImportMapTy &ImportList) {
for (auto &GlobalList : Index) {
if (GlobalList.second.SummaryList.empty())
continue;
auto GUID = GlobalList.first;
assert(GlobalList.second.SummaryList.size() == 1 &&
"Expected individual combined index to have one summary per GUID");
auto &Summary = GlobalList.second.SummaryList[0];
if (Summary->modulePath() == ModulePath)
continue;
ImportList[Summary->modulePath()].insert(GUID);
}
#ifndef NDEBUG
dumpImportListForModule(Index, ModulePath, ImportList);
#endif
}
void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index,
FunctionSummary *FS) {
for (auto &EI : FS->mutableCalls()) {
if (!EI.first.getSummaryList().empty())
continue;
auto GUID = Index.getGUIDFromOriginalID(EI.first.getGUID());
if (GUID == 0)
continue;
auto VI = Index.getValueInfo(GUID);
if (llvm::any_of(
VI.getSummaryList(),
[&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
return SummaryPtr->getSummaryKind() ==
GlobalValueSummary::GlobalVarKind;
}))
continue;
EI.first = VI;
}
}
void llvm::updateIndirectCalls(ModuleSummaryIndex &Index) {
for (const auto &Entry : Index) {
for (auto &S : Entry.second.SummaryList) {
if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
updateValueInfoForIndirectCalls(Index, FS);
}
}
}
void llvm::computeDeadSymbolsAndUpdateIndirectCalls(
ModuleSummaryIndex &Index,
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
assert(!Index.withGlobalValueDeadStripping());
if (!ComputeDead ||
GUIDPreservedSymbols.empty()) {
updateIndirectCalls(Index);
return;
}
unsigned LiveSymbols = 0;
SmallVector<ValueInfo, 128> Worklist;
Worklist.reserve(GUIDPreservedSymbols.size() * 2);
for (auto GUID : GUIDPreservedSymbols) {
ValueInfo VI = Index.getValueInfo(GUID);
if (!VI)
continue;
for (auto &S : VI.getSummaryList())
S->setLive(true);
}
for (const auto &Entry : Index) {
auto VI = Index.getValueInfo(Entry);
for (auto &S : Entry.second.SummaryList) {
if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
updateValueInfoForIndirectCalls(Index, FS);
if (S->isLive()) {
LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
Worklist.push_back(VI);
++LiveSymbols;
break;
}
}
}
auto visit = [&](ValueInfo VI, bool IsAliasee) {
if (llvm::any_of(VI.getSummaryList(),
[](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
return S->isLive();
}))
return;
if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
bool KeepAliveLinkage = false;
bool Interposable = false;
for (auto &S : VI.getSummaryList()) {
if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
S->linkage() == GlobalValue::WeakODRLinkage ||
S->linkage() == GlobalValue::LinkOnceODRLinkage)
KeepAliveLinkage = true;
else if (GlobalValue::isInterposableLinkage(S->linkage()))
Interposable = true;
}
if (!IsAliasee) {
if (!KeepAliveLinkage)
return;
if (Interposable)
report_fatal_error(
"Interposable and available_externally/linkonce_odr/weak_odr "
"symbol");
}
}
for (auto &S : VI.getSummaryList())
S->setLive(true);
++LiveSymbols;
Worklist.push_back(VI);
};
while (!Worklist.empty()) {
auto VI = Worklist.pop_back_val();
for (auto &Summary : VI.getSummaryList()) {
if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
visit(AS->getAliaseeVI(), true);
continue;
}
for (auto Ref : Summary->refs())
visit(Ref, false);
if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
for (auto Call : FS->calls())
visit(Call.first, false);
}
}
Index.setWithGlobalValueDeadStripping();
unsigned DeadSymbols = Index.size() - LiveSymbols;
LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
<< " symbols Dead \n");
NumDeadSymbols += DeadSymbols;
NumLiveSymbols += LiveSymbols;
}
void llvm::computeDeadSymbolsWithConstProp(
ModuleSummaryIndex &Index,
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
bool ImportEnabled) {
computeDeadSymbolsAndUpdateIndirectCalls(Index, GUIDPreservedSymbols,
isPrevailing);
if (ImportEnabled)
Index.propagateAttributes(GUIDPreservedSymbols);
}
void llvm::gatherImportedSummariesForModule(
StringRef ModulePath,
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
const FunctionImporter::ImportMapTy &ImportList,
std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
ModuleToSummariesForIndex[std::string(ModulePath)] =
ModuleToDefinedGVSummaries.lookup(ModulePath);
for (auto &ILI : ImportList) {
auto &SummariesForIndex =
ModuleToSummariesForIndex[std::string(ILI.first())];
const auto &DefinedGVSummaries =
ModuleToDefinedGVSummaries.lookup(ILI.first());
for (auto &GI : ILI.second) {
const auto &DS = DefinedGVSummaries.find(GI);
assert(DS != DefinedGVSummaries.end() &&
"Expected a defined summary for imported global value");
SummariesForIndex[GI] = DS->second;
}
}
}
std::error_code llvm::EmitImportsFiles(
StringRef ModulePath, StringRef OutputFilename,
const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
std::error_code EC;
raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
if (EC)
return EC;
for (auto &ILI : ModuleToSummariesForIndex)
if (ILI.first != ModulePath)
ImportsOS << ILI.first << "\n";
return std::error_code();
}
bool llvm::convertToDeclaration(GlobalValue &GV) {
LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
<< "\n");
if (Function *F = dyn_cast<Function>(&GV)) {
F->deleteBody();
F->clearMetadata();
F->setComdat(nullptr);
} else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
V->setInitializer(nullptr);
V->setLinkage(GlobalValue::ExternalLinkage);
V->clearMetadata();
V->setComdat(nullptr);
} else {
GlobalValue *NewGV;
if (GV.getValueType()->isFunctionTy())
NewGV =
Function::Create(cast<FunctionType>(GV.getValueType()),
GlobalValue::ExternalLinkage, GV.getAddressSpace(),
"", GV.getParent());
else
NewGV =
new GlobalVariable(*GV.getParent(), GV.getValueType(),
false, GlobalValue::ExternalLinkage,
nullptr, "",
nullptr, GV.getThreadLocalMode(),
GV.getType()->getAddressSpace());
NewGV->takeName(&GV);
GV.replaceAllUsesWith(NewGV);
return false;
}
if (!GV.isImplicitDSOLocal())
GV.setDSOLocal(false);
return true;
}
void llvm::thinLTOFinalizeInModule(Module &TheModule,
const GVSummaryMapTy &DefinedGlobals,
bool PropagateAttrs) {
auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
const auto &GS = DefinedGlobals.find(GV.getGUID());
if (GS == DefinedGlobals.end())
return;
if (Propagate)
if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GS->second)) {
if (Function *F = dyn_cast<Function>(&GV)) {
if (FS->fflags().ReadNone && !F->doesNotAccessMemory())
F->setDoesNotAccessMemory();
if (FS->fflags().ReadOnly && !F->onlyReadsMemory())
F->setOnlyReadsMemory();
if (FS->fflags().NoRecurse && !F->doesNotRecurse())
F->setDoesNotRecurse();
if (FS->fflags().NoUnwind && !F->doesNotThrow())
F->setDoesNotThrow();
}
}
auto NewLinkage = GS->second->linkage();
if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
GlobalValue::isLocalLinkage(NewLinkage) ||
GV.isDeclaration())
return;
if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
GV.setVisibility(GS->second->getVisibility());
if (NewLinkage == GV.getLinkage())
return;
if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
GlobalValue::isInterposableLinkage(GV.getLinkage())) {
if (!convertToDeclaration(GV))
llvm_unreachable("Expected GV to be converted");
} else {
if (NewLinkage == GlobalValue::WeakODRLinkage &&
GS->second->canAutoHide()) {
assert(GV.canBeOmittedFromSymbolTable());
GV.setVisibility(GlobalValue::HiddenVisibility);
}
LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
<< "` from " << GV.getLinkage() << " to " << NewLinkage
<< "\n");
GV.setLinkage(NewLinkage);
}
auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
GO->setComdat(nullptr);
};
for (auto &GV : TheModule)
FinalizeInModule(GV, PropagateAttrs);
for (auto &GV : TheModule.globals())
FinalizeInModule(GV);
for (auto &GV : TheModule.aliases())
FinalizeInModule(GV);
}
void llvm::thinLTOInternalizeModule(Module &TheModule,
const GVSummaryMapTy &DefinedGlobals) {
auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
if (isa<GlobalIFunc>(&GV) ||
(isa<GlobalAlias>(&GV) &&
isa<GlobalIFunc>(cast<GlobalAlias>(&GV)->getAliaseeObject())))
return true;
auto GS = DefinedGlobals.find(GV.getGUID());
if (GS == DefinedGlobals.end()) {
StringRef OrigName =
ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
std::string OrigId = GlobalValue::getGlobalIdentifier(
OrigName, GlobalValue::InternalLinkage,
TheModule.getSourceFileName());
GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
if (GS == DefinedGlobals.end()) {
GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
assert(GS != DefinedGlobals.end());
}
}
return !GlobalValue::isLocalLinkage(GS->second->linkage());
};
internalizeModule(TheModule, MustPreserveGV);
}
static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
Function *Fn = cast<Function>(GA->getAliaseeObject());
ValueToValueMapTy VMap;
Function *NewFn = CloneFunction(Fn, VMap);
NewFn->setLinkage(GA->getLinkage());
NewFn->setVisibility(GA->getVisibility());
GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
NewFn->takeName(GA);
return NewFn;
}
static void internalizeGVsAfterImport(Module &M) {
for (auto &GV : M.globals())
if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
GV.setLinkage(GlobalValue::InternalLinkage);
GV.setVisibility(GlobalValue::DefaultVisibility);
}
}
Expected<bool> FunctionImporter::importFunctions(
Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
LLVM_DEBUG(dbgs() << "Starting import for Module "
<< DestModule.getModuleIdentifier() << "\n");
unsigned ImportedCount = 0, ImportedGVCount = 0;
IRMover Mover(DestModule);
std::set<StringRef> ModuleNameOrderedList;
for (auto &FunctionsToImportPerModule : ImportList) {
ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
}
for (auto &Name : ModuleNameOrderedList) {
const auto &FunctionsToImportPerModule = ImportList.find(Name);
assert(FunctionsToImportPerModule != ImportList.end());
Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
if (!SrcModuleOrErr)
return SrcModuleOrErr.takeError();
std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
assert(&DestModule.getContext() == &SrcModule->getContext() &&
"Context mismatch");
if (Error Err = SrcModule->materializeMetadata())
return std::move(Err);
auto &ImportGUIDs = FunctionsToImportPerModule->second;
SetVector<GlobalValue *> GlobalsToImport;
for (Function &F : *SrcModule) {
if (!F.hasName())
continue;
auto GUID = F.getGUID();
auto Import = ImportGUIDs.count(GUID);
LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
<< GUID << " " << F.getName() << " from "
<< SrcModule->getSourceFileName() << "\n");
if (Import) {
if (Error Err = F.materialize())
return std::move(Err);
if (EnableImportMetadata) {
F.setMetadata(
"thinlto_src_module",
MDNode::get(DestModule.getContext(),
{MDString::get(DestModule.getContext(),
SrcModule->getSourceFileName())}));
}
GlobalsToImport.insert(&F);
}
}
for (GlobalVariable &GV : SrcModule->globals()) {
if (!GV.hasName())
continue;
auto GUID = GV.getGUID();
auto Import = ImportGUIDs.count(GUID);
LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
<< GUID << " " << GV.getName() << " from "
<< SrcModule->getSourceFileName() << "\n");
if (Import) {
if (Error Err = GV.materialize())
return std::move(Err);
ImportedGVCount += GlobalsToImport.insert(&GV);
}
}
for (GlobalAlias &GA : SrcModule->aliases()) {
if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
continue;
auto GUID = GA.getGUID();
auto Import = ImportGUIDs.count(GUID);
LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
<< GUID << " " << GA.getName() << " from "
<< SrcModule->getSourceFileName() << "\n");
if (Import) {
if (Error Err = GA.materialize())
return std::move(Err);
GlobalObject *GO = GA.getAliaseeObject();
if (Error Err = GO->materialize())
return std::move(Err);
auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << GO->getGUID() << " "
<< GO->getName() << " from "
<< SrcModule->getSourceFileName() << "\n");
if (EnableImportMetadata) {
Fn->setMetadata(
"thinlto_src_module",
MDNode::get(DestModule.getContext(),
{MDString::get(DestModule.getContext(),
SrcModule->getSourceFileName())}));
}
GlobalsToImport.insert(Fn);
}
}
UpgradeDebugInfo(*SrcModule);
SrcModule->setPartialSampleProfileRatio(Index);
if (renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
&GlobalsToImport))
return true;
if (PrintImports) {
for (const auto *GV : GlobalsToImport)
dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
<< " from " << SrcModule->getSourceFileName() << "\n";
}
if (Error Err = Mover.move(std::move(SrcModule),
GlobalsToImport.getArrayRef(), nullptr,
true))
report_fatal_error(Twine("Function Import: link error: ") +
toString(std::move(Err)));
ImportedCount += GlobalsToImport.size();
NumImportedModules++;
}
internalizeGVsAfterImport(DestModule);
NumImportedFunctions += (ImportedCount - ImportedGVCount);
NumImportedGlobalVars += ImportedGVCount;
LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
<< " functions for Module "
<< DestModule.getModuleIdentifier() << "\n");
LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
<< " global variables for Module "
<< DestModule.getModuleIdentifier() << "\n");
return ImportedCount;
}
static bool doImportingForModule(Module &M) {
if (SummaryFile.empty())
report_fatal_error("error: -function-import requires -summary-file\n");
Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
getModuleSummaryIndexForFile(SummaryFile);
if (!IndexPtrOrErr) {
logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
"Error loading file '" + SummaryFile + "': ");
return false;
}
std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
FunctionImporter::ImportMapTy ImportList;
if (ImportAllIndex)
ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
ImportList);
else
ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
ImportList);
for (auto &I : *Index) {
for (auto &S : I.second.SummaryList) {
if (GlobalValue::isLocalLinkage(S->linkage()))
S->setLinkage(GlobalValue::ExternalLinkage);
}
}
if (renameModuleForThinLTO(M, *Index, false,
nullptr)) {
errs() << "Error renaming module\n";
return false;
}
auto ModuleLoader = [&M](StringRef Identifier) {
return loadFile(std::string(Identifier), M.getContext());
};
FunctionImporter Importer(*Index, ModuleLoader,
false);
Expected<bool> Result = Importer.importFunctions(M, ImportList);
if (!Result) {
logAllUnhandledErrors(Result.takeError(), errs(),
"Error importing module: ");
return false;
}
return *Result;
}
PreservedAnalyses FunctionImportPass::run(Module &M,
ModuleAnalysisManager &AM) {
if (!doImportingForModule(M))
return PreservedAnalyses::all();
return PreservedAnalyses::none();
}