ThinLTOCodeGenerator.cpp [plain text]
#include "llvm/LTO/ThinLTOCodeGenerator.h"
#ifdef HAVE_LLVM_REVISION
#include "LLVMLTORevision.h"
#endif
#include "UpdateCompilerUsed.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Analysis/ModuleSummaryAnalysis.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Linker/Linker.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Object/IRObjectFile.h"
#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CachePruning.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SHA1.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/FunctionImport.h"
#include "llvm/Transforms/IPO/Internalize.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/ObjCARC.h"
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
#include <numeric>
using namespace llvm;
#define DEBUG_TYPE "thinlto"
namespace llvm {
extern cl::opt<bool> LTODiscardValueNames;
}
namespace {
static cl::opt<int> ThreadCount("threads",
cl::init(std::thread::hardware_concurrency()));
#if defined(__APPLE__)
#include <sys/param.h>
#include <sys/sysctl.h>
static int getNumCores() {
if (ThreadCount.getNumOccurrences())
return ThreadCount;
uint32_t count;
size_t len = sizeof(count);
sysctlbyname("hw.physicalcpu", &count, &len, NULL, 0);
if (count < 1) {
int nm[2];
nm[0] = CTL_HW;
nm[1] = HW_AVAILCPU;
sysctl(nm, 2, &count, &len, NULL, 0);
if (count < 1) {
count = std::thread::hardware_concurrency();
}
}
return count;
}
#else
static int getNumCores() { return ThreadCount; }
#endif
static void diagnosticHandler(const DiagnosticInfo &DI) {
DiagnosticPrinterRawOStream DP(errs());
DI.print(DP);
errs() << '\n';
}
static std::unique_ptr<Module>
loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
bool Lazy) {
SMDiagnostic Err;
ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
if (Lazy) {
ModuleOrErr =
getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context,
Lazy);
} else {
ModuleOrErr = parseBitcodeFile(Buffer, Context);
}
if (std::error_code EC = ModuleOrErr.getError()) {
Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
EC.message());
Err.print("ThinLTO", errs());
report_fatal_error("Can't load module, abort.");
}
return std::move(ModuleOrErr.get());
}
static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
unsigned count, StringRef Suffix) {
if (TempDir.empty())
return;
auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix;
std::error_code EC;
raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None);
if (EC)
report_fatal_error(Twine("Failed to open ") + SaveTempPath +
" to save optimized bitcode\n");
WriteBitcodeToFile(&TheModule, OS, true);
}
bool IsFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList,
const ModuleSummaryIndex &Index,
StringRef ModulePath) {
auto FirstDefForLinker = llvm::find_if(
GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
auto Linkage = Summary->linkage();
return !GlobalValue::isAvailableExternallyLinkage(Linkage);
});
if ((*FirstDefForLinker)->modulePath() != ModulePath)
return false;
if (llvm::any_of(
GVSummaryList,
[](const std::unique_ptr<GlobalValueSummary> &Summary) {
auto Linkage = Summary->linkage();
return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
!GlobalValue::isWeakForLinker(Linkage);
}))
return false;
return true;
}
static GlobalValue::LinkageTypes
ResolveODR(const ModuleSummaryIndex &Index,
const FunctionImporter::ExportSetTy &ExportList,
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
StringRef ModuleIdentifier, GlobalValue::GUID GUID,
const GlobalValueSummary &GV) {
auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
return GVSummaryList.size() > 1;
};
auto OriginalLinkage = GV.linkage();
switch (OriginalLinkage) {
case GlobalValue::ExternalLinkage:
case GlobalValue::AvailableExternallyLinkage:
case GlobalValue::AppendingLinkage:
case GlobalValue::InternalLinkage:
case GlobalValue::PrivateLinkage:
case GlobalValue::ExternalWeakLinkage:
case GlobalValue::CommonLinkage:
case GlobalValue::LinkOnceAnyLinkage:
case GlobalValue::WeakAnyLinkage:
break;
case GlobalValue::LinkOnceODRLinkage:
case GlobalValue::WeakODRLinkage: {
auto &GVSummaryList = Index.findGlobalValueSummaryList(GUID)->second;
if (!HasMultipleCopies(GVSummaryList)) {
if (GlobalValue::isDiscardableIfUnused(OriginalLinkage) &&
(ExportList.count(GUID) || GUIDPreservedSymbols.count(GUID)))
return GlobalValue::WeakODRLinkage;
break;
}
if (IsFirstDefinitionForLinker(GVSummaryList, Index, ModuleIdentifier))
return GlobalValue::WeakODRLinkage;
else if (isa<AliasSummary>(&GV))
return OriginalLinkage;
return GlobalValue::AvailableExternallyLinkage;
}
}
return OriginalLinkage;
}
static void ResolveODR(
const ModuleSummaryIndex &Index,
const FunctionImporter::ExportSetTy &ExportList,
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
const GVSummaryMapTy &DefinedGlobals, StringRef ModuleIdentifier,
std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
if (Index.modulePaths().size() == 1)
return;
DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
for (auto &GA : DefinedGlobals) {
if (auto AS = dyn_cast<AliasSummary>(GA.second))
GlobalInvolvedWithAlias.insert(&AS->getAliasee());
}
for (auto &GV : DefinedGlobals) {
if (GlobalInvolvedWithAlias.count(GV.second))
continue;
auto NewLinkage =
ResolveODR(Index, ExportList, GUIDPreservedSymbols, ModuleIdentifier, GV.first, *GV.second);
if (NewLinkage != GV.second->linkage()) {
ResolvedODR[GV.first] = NewLinkage;
}
}
}
void fixupODR(
Module &TheModule,
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
for (auto &GV : TheModule) {
auto NewLinkage = ResolvedODR.find(GV.getGUID());
if (NewLinkage == ResolvedODR.end())
continue;
DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
<< GV.getLinkage() << " to " << NewLinkage->second << "\n");
GV.setLinkage(NewLinkage->second);
}
for (auto &GV : TheModule.globals()) {
auto NewLinkage = ResolvedODR.find(GV.getGUID());
if (NewLinkage == ResolvedODR.end())
continue;
DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
<< GV.getLinkage() << " to " << NewLinkage->second << "\n");
GV.setLinkage(NewLinkage->second);
}
for (auto &GV : TheModule.aliases()) {
auto NewLinkage = ResolvedODR.find(GV.getGUID());
if (NewLinkage == ResolvedODR.end())
continue;
DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
<< GV.getLinkage() << " to " << NewLinkage->second << "\n");
GV.setLinkage(NewLinkage->second);
}
}
static StringMap<MemoryBufferRef>
generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
StringMap<MemoryBufferRef> ModuleMap;
for (auto &ModuleBuffer : Modules) {
assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
ModuleMap.end() &&
"Expect unique Buffer Identifier");
ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
}
return ModuleMap;
}
class ModuleLoader {
LLVMContext &Context;
StringMap<MemoryBufferRef> &ModuleMap;
public:
ModuleLoader(LLVMContext &Context, StringMap<MemoryBufferRef> &ModuleMap)
: Context(Context), ModuleMap(ModuleMap) {}
std::unique_ptr<Module> operator()(StringRef Identifier) {
return loadModuleFromBuffer(ModuleMap[Identifier], Context, true);
}
};
static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
if (renameModuleForThinLTO(TheModule, Index))
report_fatal_error("renameModuleForThinLTO failed");
}
static void
crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
StringMap<MemoryBufferRef> &ModuleMap,
const FunctionImporter::ImportMapTy &ImportList) {
ModuleLoader Loader(TheModule.getContext(), ModuleMap);
FunctionImporter Importer(Index, Loader);
Importer.importFunctions(TheModule, ImportList);
}
static void optimizeModule(Module &TheModule, TargetMachine &TM) {
PassManagerBuilder PMB;
PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
PMB.Inliner = createFunctionInliningPass();
PMB.OptLevel = 3;
PMB.LoopVectorize = true;
PMB.SLPVectorize = true;
PMB.VerifyInput = true;
PMB.VerifyOutput = false;
legacy::PassManager PM;
PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
PMB.populateThinLTOPassManager(PM);
PM.run(TheModule);
}
static DenseSet<const GlobalValue *> computePreservedSymbolsForModule(
Module &TheModule, const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
const FunctionImporter::ExportSetTy &ExportList) {
DenseSet<const GlobalValue *> PreservedGV;
if (GUIDPreservedSymbols.empty())
return PreservedGV;
auto AddPreserveGV = [&](const GlobalValue &GV) {
auto GUID = GV.getGUID();
if (GUIDPreservedSymbols.count(GUID) || ExportList.count(GUID))
PreservedGV.insert(&GV);
};
for (auto &GV : TheModule)
AddPreserveGV(GV);
for (auto &GV : TheModule.globals())
AddPreserveGV(GV);
for (auto &GV : TheModule.aliases())
AddPreserveGV(GV);
return PreservedGV;
}
static void
doInternalizeModule(Module &TheModule, const TargetMachine &TM,
const DenseSet<const GlobalValue *> &PreservedGV) {
if (PreservedGV.empty()) {
return;
}
StringSet<> AsmUndefinedRefs;
object::IRObjectFile::CollectAsmUndefinedRefs(
Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
[&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
if (Flags & object::BasicSymbolRef::SF_Undefined)
AsmUndefinedRefs.insert(Name);
});
UpdateCompilerUsed(TheModule, TM, AsmUndefinedRefs);
auto MustPreserveGV =
[&](const GlobalValue &GV) -> bool { return PreservedGV.count(&GV); };
llvm::internalizeModule(TheModule, MustPreserveGV);
}
static DenseSet<GlobalValue::GUID>
computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
const Triple &TheTriple) {
DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
for (auto &Entry : PreservedSymbols) {
StringRef Name = Entry.first();
if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
Name = Name.drop_front();
GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
}
return GUIDPreservedSymbols;
}
std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
TargetMachine &TM) {
SmallVector<char, 128> OutputBuffer;
{
raw_svector_ostream OS(OutputBuffer);
legacy::PassManager PM;
PM.add(createObjCARCContractPass());
if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
true))
report_fatal_error("Failed to setup codegen");
PM.run(TheModule);
}
return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
}
class ModuleCacheEntry {
SmallString<128> EntryPath;
public:
ModuleCacheEntry(
StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
const FunctionImporter::ImportMapTy &ImportList,
const FunctionImporter::ExportSetTy &ExportList,
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
const GVSummaryMapTy &DefinedFunctions,
const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
if (CachePath.empty())
return;
SHA1 Hasher;
Hasher.update(LLVM_VERSION_STRING);
#ifdef HAVE_LLVM_REVISION
Hasher.update(LLVM_REVISION);
#endif
auto ModHash = Index.getModuleHash(ModuleID);
Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
for (auto F : ExportList)
Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
for (auto &Entry : ImportList) {
auto ModHash = Index.getModuleHash(Entry.first());
Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
}
for (auto &Entry : ResolvedODR) {
Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
sizeof(GlobalValue::GUID)));
Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
sizeof(GlobalValue::LinkageTypes)));
}
for (auto &Entry : PreservedSymbols) {
if (DefinedFunctions.count(Entry))
Hasher.update(
ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
}
sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
}
StringRef getEntryPath() { return EntryPath; }
ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
if (EntryPath.empty())
return std::error_code();
return MemoryBuffer::getFile(EntryPath);
}
std::unique_ptr<MemoryBuffer>
write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
if (EntryPath.empty())
return OutputBuffer;
SmallString<128> TempFilename;
int TempFD;
std::error_code EC =
sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
if (EC) {
errs() << "Error: " << EC.message() << "\n";
report_fatal_error("ThinLTO: Can't get a temporary file");
}
{
raw_fd_ostream OS(TempFD, true);
OS << OutputBuffer->getBuffer();
}
EC = sys::fs::rename(TempFilename, EntryPath);
if (EC) {
sys::fs::remove(TempFilename);
raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
if (EC)
report_fatal_error(Twine("Failed to open ") + EntryPath +
" to save cached entry\n");
OS << OutputBuffer->getBuffer();
}
auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
if (auto EC = ReloadedBufferOrErr.getError()) {
errs() << "error: can't reload cached file '" << EntryPath
<< "': " << EC.message() << "\n";
return OutputBuffer;
}
return std::move(*ReloadedBufferOrErr);
}
};
static std::unique_ptr<MemoryBuffer> ProcessThinLTOModule(
Module &TheModule, const ModuleSummaryIndex &Index,
StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
const FunctionImporter::ImportMapTy &ImportList,
const FunctionImporter::ExportSetTy &ExportList,
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
ThinLTOCodeGenerator::CachingOptions CacheOptions, bool DisableCodeGen,
StringRef SaveTempsDir, unsigned count) {
auto PreservedGV = computePreservedSymbolsForModule(
TheModule, GUIDPreservedSymbols, ExportList);
bool SingleModule = (ModuleMap.size() == 1);
if (!SingleModule) {
promoteModule(TheModule, Index);
fixupODR(TheModule, ResolvedODR);
saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
}
doInternalizeModule(TheModule, TM, PreservedGV);
saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
if (!SingleModule) {
crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
}
optimizeModule(TheModule, TM);
saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
if (DisableCodeGen) {
SmallVector<char, 128> OutputBuffer;
{
raw_svector_ostream OS(OutputBuffer);
ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
}
return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
}
return codegenModule(TheModule, TM);
}
static void initTMBuilder(TargetMachineBuilder &TMBuilder,
const Triple &TheTriple) {
if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
if (TheTriple.getArch() == llvm::Triple::x86_64)
TMBuilder.MCpu = "core2";
else if (TheTriple.getArch() == llvm::Triple::x86)
TMBuilder.MCpu = "yonah";
else if (TheTriple.getArch() == llvm::Triple::aarch64)
TMBuilder.MCpu = "cyclone";
}
TMBuilder.TheTriple = std::move(TheTriple);
}
}
void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
MemoryBufferRef Buffer(Data, Identifier);
if (Modules.empty()) {
LLVMContext Context;
Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
initTMBuilder(TMBuilder, Triple(TheTriple));
}
#ifndef NDEBUG
else {
LLVMContext Context;
assert(TMBuilder.TheTriple.str() ==
getBitcodeTargetTriple(Buffer, Context) &&
"ThinLTO modules with different triple not supported");
}
#endif
Modules.push_back(Buffer);
}
void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
PreservedSymbols.insert(Name);
}
void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
PreservedSymbols.insert(Name);
}
std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
std::string ErrMsg;
const Target *TheTarget =
TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
if (!TheTarget) {
report_fatal_error("Can't load target for this Triple: " + ErrMsg);
}
SubtargetFeatures Features(MAttr);
Features.getDefaultSubtargetFeatures(TheTriple);
std::string FeatureStr = Features.getString();
return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
CodeModel::Default, CGOptLevel));
}
std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
uint64_t NextModuleId = 0;
for (auto &ModuleBuffer : Modules) {
ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
diagnosticHandler);
if (std::error_code EC = ObjOrErr.getError()) {
errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
<< EC.message() << "\n";
return nullptr;
}
auto Index = (*ObjOrErr)->takeIndex();
if (CombinedIndex) {
CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
} else {
CombinedIndex = std::move(Index);
}
}
return CombinedIndex;
}
void ThinLTOCodeGenerator::promote(Module &TheModule,
ModuleSummaryIndex &Index) {
auto ModuleCount = Index.modulePaths().size();
auto ModuleIdentifier = TheModule.getModuleIdentifier();
StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
ExportLists);
auto &ExportList = ExportLists[ModuleIdentifier];
auto GUIDPreservedSymbols =
computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
ResolveODR(Index, ExportList, GUIDPreservedSymbols, ModuleToDefinedGVSummaries[ModuleIdentifier],
ModuleIdentifier, ResolvedODR);
fixupODR(TheModule, ResolvedODR);
promoteModule(TheModule, Index);
}
void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
ModuleSummaryIndex &Index) {
auto ModuleMap = generateModuleMap(Modules);
auto ModuleCount = Index.modulePaths().size();
StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
ExportLists);
auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
}
void ThinLTOCodeGenerator::internalize(Module &TheModule,
ModuleSummaryIndex &Index) {
initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
auto ModuleCount = Index.modulePaths().size();
auto ModuleIdentifier = TheModule.getModuleIdentifier();
auto GUIDPreservedSymbols =
computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
ExportLists);
auto &ExportList = ExportLists[ModuleIdentifier];
auto PreservedGV = computePreservedSymbolsForModule(
TheModule, GUIDPreservedSymbols, ExportList);
doInternalizeModule(TheModule, *TMBuilder.create(), PreservedGV);
}
void ThinLTOCodeGenerator::optimize(Module &TheModule) {
initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
optimizeModule(TheModule, *TMBuilder.create());
}
std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
return codegenModule(TheModule, *TMBuilder.create());
}
void ThinLTOCodeGenerator::run() {
if (CodeGenOnly) {
ThreadPool Pool;
assert(ProducedBinaries.empty() && "The generator should not be reused");
ProducedBinaries.resize(Modules.size());
int count = 0;
for (auto &ModuleBuffer : Modules) {
Pool.async([&](int count) {
LLVMContext Context;
Context.setDiscardValueNames(LTODiscardValueNames);
auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
ProducedBinaries[count] = codegen(*TheModule);
}, count++);
}
return;
}
auto Index = linkCombinedIndex();
if (!SaveTempsDir.empty()) {
auto SaveTempPath = SaveTempsDir + "index.bc";
std::error_code EC;
raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
if (EC)
report_fatal_error(Twine("Failed to open ") + SaveTempPath +
" to save optimized bitcode\n");
WriteIndexToFile(*Index, OS);
}
assert(ProducedBinaries.empty() && "The generator should not be reused");
ProducedBinaries.resize(Modules.size());
auto ModuleMap = generateModuleMap(Modules);
auto ModuleCount = Modules.size();
StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
ExportLists);
auto GUIDPreservedSymbols =
computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries)
ExportLists[DefinedGVSummaries.first()];
std::vector<int> ModulesOrdering;
ModulesOrdering.resize(Modules.size());
std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
[&](int LeftIndex, int RightIndex) {
auto LSize = Modules[LeftIndex].getBufferSize();
auto RSize = Modules[RightIndex].getBufferSize();
return LSize > RSize;
});
{
ThreadPool Pool(getNumCores());
for (auto IndexCount : ModulesOrdering) {
auto &ModuleBuffer = Modules[IndexCount];
Pool.async([&](int count) {
auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
auto &ExportList = ExportLists[ModuleIdentifier];
auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
ResolveODR(*Index, ExportList, GUIDPreservedSymbols, DefinedFunctions, ModuleIdentifier,
ResolvedODR);
ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
ImportLists[ModuleIdentifier], ExportList,
ResolvedODR, DefinedFunctions,
GUIDPreservedSymbols);
{
auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
<< CacheEntry.getEntryPath() << "' for buffer " << count
<< " " << ModuleIdentifier << "\n");
if (ErrOrBuffer) {
ProducedBinaries[count] = std::move(ErrOrBuffer.get());
return;
}
}
LLVMContext Context;
Context.setDiscardValueNames(LTODiscardValueNames);
Context.enableDebugTypeODRUniquing();
auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
auto &ImportList = ImportLists[ModuleIdentifier];
auto OutputBuffer = ProcessThinLTOModule(
*TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
ExportList, GUIDPreservedSymbols, ResolvedODR, CacheOptions,
DisableCodeGen, SaveTempsDir, count);
OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
ProducedBinaries[count] = std::move(OutputBuffer);
}, IndexCount);
}
}
CachePruning(CacheOptions.Path)
.setPruningInterval(CacheOptions.PruningInterval)
.setEntryExpiration(CacheOptions.Expiration)
.setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
.prune();
if (llvm::AreStatisticsEnabled())
llvm::PrintStatistics();
}