17 #ifdef HAVE_LLVM_REVISION
18 #include "LLVMLTORevision.h"
62 #define DEBUG_TYPE "thinlto"
77 setupOptimizationRemarks(
LLVMContext &Ctx,
int Count) {
84 std::string FileName =
87 auto DiagnosticOutputFile =
92 llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
93 DiagnosticOutputFile->keep();
94 return std::move(DiagnosticOutputFile);
103 std::string SaveTempPath = (TempDir +
llvm::utostr(count) + Suffix).str();
108 " to save optimized bitcode\n");
116 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
117 auto Linkage = Summary->linkage();
121 if (StrongDefForLinker != GVSummaryList.end())
122 return StrongDefForLinker->get();
126 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
127 auto Linkage = Summary->linkage();
131 if (FirstDefForLinker == GVSummaryList.end())
133 return FirstDefForLinker->get();
139 static void computePrevailingCopies(
143 return GVSummaryList.size() > 1;
146 for (
auto &
I : Index) {
147 if (HasMultipleCopies(
I.second))
148 PrevailingCopy[
I.first] = getFirstDefinitionForLinker(
I.second);
153 generateModuleMap(
const std::vector<ThinLTOBuffer> &Modules) {
155 for (
auto &ModuleBuffer : Modules) {
156 assert(ModuleMap.
find(ModuleBuffer.getBufferIdentifier()) ==
158 "Expect unique Buffer Identifier");
159 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
169 static std::unique_ptr<Module>
171 bool Lazy,
bool IsImporting) {
186 return std::move(ModuleOrErr.
get());
193 auto Loader = [&](
StringRef Identifier) {
194 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.
getContext(),
199 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
237 computeGUIDPreservedSymbols(
const StringSet<> &PreservedSymbols,
238 const Triple &TheTriple) {
240 for (
auto &Entry : PreservedSymbols) {
246 return GUIDPreservedSymbols;
249 std::unique_ptr<MemoryBuffer> codegenModule(
Module &TheModule,
270 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
274 class ModuleCacheEntry {
285 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
289 if (CachePath.
empty())
315 auto AddUnsigned = [&](
unsigned I) {
325 Hasher.
update(LLVM_VERSION_STRING);
326 #ifdef HAVE_LLVM_REVISION
327 Hasher.
update(LLVM_REVISION);
331 AddString(TMBuilder.
MCpu);
340 AddString(TMBuilder.
MAttr);
344 AddUnsigned(OptLevel);
347 for (
auto F : ExportList)
352 for (
auto &Entry : ImportList) {
358 for (
auto &Entry : ResolvedODR) {
366 for (
auto &Entry : PreservedSymbols) {
367 if (DefinedFunctions.count(Entry))
376 StringRef getEntryPath() {
return EntryPath; }
380 if (EntryPath.empty())
381 return std::error_code();
387 if (EntryPath.empty())
396 errs() <<
"Error: " << EC.message() <<
"\n";
410 " to save cached entry\n");
416 static std::unique_ptr<MemoryBuffer>
424 bool DisableCodeGen,
StringRef SaveTempsDir,
425 unsigned OptLevel,
unsigned count) {
428 bool SingleModule = (ModuleMap.
size() == 1);
431 promoteModule(TheModule, Index);
437 saveTempBitcode(TheModule, SaveTempsDir, count,
".1.promoted.bc");
442 if (!ExportList.empty() || !GUIDPreservedSymbols.
empty()) {
448 saveTempBitcode(TheModule, SaveTempsDir, count,
".2.internalized.bc");
451 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
454 saveTempBitcode(TheModule, SaveTempsDir, count,
".3.imported.bc");
457 optimizeModule(TheModule, TM, OptLevel);
459 saveTempBitcode(TheModule, SaveTempsDir, count,
".4.opt.bc");
461 if (DisableCodeGen) {
470 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
473 return codegenModule(TheModule, TM);
481 static void resolveWeakForLinkerInIndex(
483 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
487 computePrevailingCopies(Index, PrevailingCopy);
490 const auto &Prevailing = PrevailingCopy.
find(GUID);
492 if (Prevailing == PrevailingCopy.
end())
494 return Prevailing->second == S;
497 auto recordNewLinkage = [&](
StringRef ModuleIdentifier,
500 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
508 const Triple &TheTriple) {
513 TMBuilder.
MCpu =
"core2";
515 TMBuilder.
MCpu =
"yonah";
517 TMBuilder.
MCpu =
"cyclone";
519 TMBuilder.
TheTriple = std::move(TheTriple);
526 if (Modules.empty()) {
533 TripleStr = *TripleOrErr;
534 Triple TheTriple(TripleStr);
535 initTMBuilder(TMBuilder,
Triple(TheTriple));
544 TripleStr = *TripleOrErr;
546 "ThinLTO modules with different triple not supported");
549 Modules.push_back(Buffer);
553 PreservedSymbols.insert(Name);
560 PreservedSymbols.insert(Name);
575 std::string FeatureStr = Features.
getString();
587 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
588 uint64_t NextModuleId = 0;
589 for (
auto &ModuleBuffer : Modules) {
592 ModuleBuffer.getMemBuffer());
597 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
600 auto Index = (*ObjOrErr)->takeIndex();
602 CombinedIndex->
mergeFrom(std::move(Index), ++NextModuleId);
604 CombinedIndex = std::move(Index);
607 return CombinedIndex;
624 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
634 ExportLists, &DeadSymbols);
638 resolveWeakForLinkerInIndex(Index, ResolvedODR);
641 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
646 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
647 return (ExportList != ExportLists.
end() &&
648 ExportList->second.count(GUID)) ||
649 GUIDPreservedSymbols.
count(GUID);
653 promoteModule(TheModule, Index);
661 auto ModuleMap = generateModuleMap(Modules);
669 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
679 ExportLists, &DeadSymbols);
682 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
690 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
704 ImportLists[ModulePath],
705 ModuleToSummariesForIndex);
727 if ((EC =
EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
729 " to save imports lists\n");
742 auto GUIDPreservedSymbols =
743 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.
TheTriple);
756 ExportLists, &DeadSymbols);
757 auto &ExportList = ExportLists[ModuleIdentifier];
761 if (ExportList.empty() && GUIDPreservedSymbols.
empty())
766 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
767 return (ExportList != ExportLists.
end() &&
768 ExportList->second.count(GUID)) ||
769 GUIDPreservedSymbols.
count(GUID);
773 ModuleToDefinedGVSummaries[ModuleIdentifier]);
783 optimizeModule(TheModule, *TMBuilder.
create(), OptLevel);
791 return codegenModule(TheModule, *TMBuilder.
create());
807 if (!CacheEntryPath.
empty()) {
811 return OutputPath.
str();
815 return OutputPath.
str();
819 errs() <<
"error: can't link or copy from cached entry '" << CacheEntryPath
820 <<
"' to '" << OutputPath <<
"'\n";
828 return OutputPath.
str();
834 assert(ProducedBinaries.empty() &&
"The generator should not be reused");
835 if (SavedObjectsDirectoryPath.empty())
836 ProducedBinaries.resize(Modules.size());
843 ProducedBinaryFiles.resize(Modules.size());
850 for (
auto &ModuleBuffer : Modules) {
851 Pool.
async([&](
int count) {
857 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(),
Context,
false,
861 auto OutputBuffer =
codegen(*TheModule);
862 if (SavedObjectsDirectoryPath.empty())
863 ProducedBinaries[count] = std::move(OutputBuffer);
866 count,
"", SavedObjectsDirectoryPath, *OutputBuffer);
877 if (!SaveTempsDir.
empty()) {
878 auto SaveTempPath = SaveTempsDir +
"index.bc";
883 " to save optimized bitcode\n");
889 auto ModuleMap = generateModuleMap(Modules);
890 auto ModuleCount = Modules.size();
898 auto GUIDPreservedSymbols =
899 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.
TheTriple);
909 ExportLists, &DeadSymbols);
919 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
922 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
923 return (ExportList != ExportLists.
end() &&
924 ExportList->second.count(GUID)) ||
925 GUIDPreservedSymbols.
count(GUID);
935 for (
auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
936 ExportLists[DefinedGVSummaries.first()];
937 ResolvedODR[DefinedGVSummaries.first()];
943 std::vector<int> ModulesOrdering;
944 ModulesOrdering.resize(Modules.size());
945 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
946 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
947 [&](
int LeftIndex,
int RightIndex) {
948 auto LSize = Modules[LeftIndex].getBuffer().size();
949 auto RSize = Modules[RightIndex].getBuffer().size();
950 return LSize > RSize;
956 for (
auto IndexCount : ModulesOrdering) {
957 auto &ModuleBuffer = Modules[IndexCount];
958 Pool.
async([&](
int count) {
959 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
960 auto &ExportList = ExportLists[ModuleIdentifier];
962 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
965 ModuleCacheEntry CacheEntry(CacheOptions.
Path, *Index, ModuleIdentifier,
966 ImportLists[ModuleIdentifier], ExportList,
967 ResolvedODR[ModuleIdentifier],
968 DefinedFunctions, GUIDPreservedSymbols,
969 OptLevel, TMBuilder);
970 auto CacheEntryPath = CacheEntry.getEntryPath();
973 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
974 DEBUG(
dbgs() <<
"Cache " << (ErrOrBuffer ?
"hit" :
"miss") <<
" '"
975 << CacheEntryPath <<
"' for buffer " << count <<
" "
976 << ModuleIdentifier <<
"\n");
980 if (SavedObjectsDirectoryPath.empty())
981 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
984 count, CacheEntryPath, SavedObjectsDirectoryPath,
993 auto DiagFileOrErr = setupOptimizationRemarks(Context, count);
994 if (!DiagFileOrErr) {
995 errs() <<
"Error: " <<
toString(DiagFileOrErr.takeError()) <<
"\n";
1002 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(),
Context,
false,
1006 saveTempBitcode(*TheModule, SaveTempsDir, count,
".0.original.bc");
1008 auto &ImportList = ImportLists[ModuleIdentifier];
1010 auto OutputBuffer = ProcessThinLTOModule(
1011 *TheModule, *Index, ModuleMap, *TMBuilder.
create(), ImportList,
1012 ExportList, GUIDPreservedSymbols,
1013 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1014 DisableCodeGen, SaveTempsDir, OptLevel,
count);
1017 CacheEntry.write(*OutputBuffer);
1019 if (SavedObjectsDirectoryPath.empty()) {
1021 if (!CacheEntryPath.empty()) {
1027 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1028 if (
auto EC = ReloadedBufferOrErr.getError()) {
1031 errs() <<
"error: can't reload cached file '" << CacheEntryPath
1032 <<
"': " << EC.message() <<
"\n";
1034 OutputBuffer = std::move(*ReloadedBufferOrErr);
1037 ProducedBinaries[
count] = std::move(OutputBuffer);
1041 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Represents either an error or a value T.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
List of global value summary structures for a particular value held in the GlobalValueMap.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
CodeGenOpt::Level CGOptLevel
void setDiagnosticsOutputFile(std::unique_ptr< yaml::Output > F)
Set the diagnostics output file used for optimization diagnostics.
void promote(Module &Module, ModuleSummaryIndex &Index)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
A Module instance is used to store all the information related to an LLVM module. ...
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
This is the interface to build a ModuleSummaryIndex for a module.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This file provides a bitcode writing pass.
Implements a dense probed hash-table based set.
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
unsigned DataSections
Emit data into separate sections.
std::unique_ptr< TargetMachine > create() const
Analysis providing profile information.
static Expected< std::unique_ptr< ModuleSummaryIndexObjectFile > > create(MemoryBufferRef Object)
Parse module summary index in the given memory buffer.
void enableDebugTypeODRUniquing()
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
CachePruning & setEntryExpiration(std::chrono::seconds ExpireAfter)
Define the expiration for a file.
iterator find(StringRef Key)
StringRef getBuffer() const
A raw_ostream that writes to an SmallVector or SmallString.
Implementation of the target library information.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
const std::string & str() const
A class that wrap the SHA1 algorithm.
Error takeError()
Take ownership of the stored error.
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void addModule(StringRef Identifier, StringRef Data)
Add given module to the code generator.
Base class for error info classes.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Pass * Inliner
Inliner - Specifies the inliner to use.
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI)
Direct function to compute a ModuleSummaryIndex from a given module.
Wrapper around MemoryBufferRef, owning the identifier.
const Triple & getTargetTriple() const
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
unsigned MaxPercentageOfAvailableSpace
std::unordered_set< GlobalValue::GUID > ExportSetTy
The set contains an entry for every global value the module exports.
std::string toString(Error E)
Write all error messages (if any) in E to a string.
void add(Pass *P) override
Add a pass to the queue of passes to run.
std::unique_ptr< MemoryBuffer > codegen(Module &Module)
Perform ThinLTO CodeGen.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void setDiagnosticHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
MemoryBufferRef getMemBuffer() const
Tagged union holding either a T or a Error.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
StringRef result()
Return a reference to the current raw 160-bits SHA1 for the digested data since the last call to init...
void run()
Process all the modules that were added to the code generator in parallel.
static std::string toHex(StringRef Input)
Convert buffer Input to its hexadecimal representation.
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
Pass * createObjCARCContractPass()
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
unsigned FunctionSections
Emit functions into separate sections.
static std::string utostr(uint64_t X, bool isNeg=false)
A ThreadPool for asynchronous parallel execution on a defined number of threads.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
void update(ArrayRef< uint8_t > Data)
Digest more data.
bool isWeakForLinker() const
PassManager manages ModulePassManagers.
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
std::shared_future< VoidTy > async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
DebuggerKind DebuggerTuning
Which debugger to tune for.
void crossReferenceSymbol(StringRef Name)
Adds to a list of all global symbols that are cross-referenced between ThinLTO files.
initializer< Ty > init(const Ty &Val)
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void gatherImportedSummariesForModule(StringRef ModulePath, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
void optimize(Module &Module)
Perform post-importing ThinLTO optimizations.
This is an important class for using LLVM in a threaded context.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
CachePruning & setMaxSize(unsigned Percentage)
Define the maximum size for the cache directory, in terms of percentage of the available space on the...
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Helper to gather options relevant to the target machine creation.
virtual TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
Function and variable summary information to aid decisions and implementation of importing.
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, StringMap< FunctionImporter::ImportMapTy > &ImportLists, StringMap< FunctionImporter::ExportSetTy > &ExportLists, const DenseSet< GlobalValue::GUID > *DeadSymbols=nullptr)
Compute all the imports and exports for every module in the Index.
static void write(bool isBE, void *P, T V)
bool prune()
Peform pruning using the supplied options, returns true if pruning occured, i.e.
std::string getString() const
Features string accessors.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
bool is_directory(file_status status)
Does status represent a directory?
Triple - Helper class for working with autoconf configuration names.
static std::string writeGeneratedObject(int count, StringRef CacheEntryPath, StringRef SavedObjectsDirectoryPath, const MemoryBuffer &OutputBuffer)
Write out the generated object file, either from CacheEntryPath or from OutputBuffer, preferring hard-link when possible.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, CodeModel::Model CM=CodeModel::Default, CodeGenOpt::Level OL=CodeGenOpt::Default) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, CodeGenFileType, bool=true, AnalysisID=nullptr, AnalysisID=nullptr, AnalysisID=nullptr, AnalysisID=nullptr, MachineFunctionInitializer *=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, DenseSet< const GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
reference get()
Returns a reference to the stored T value.
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const FunctionImporter::ImportMapTy &ModuleImports)
Emit into OutputFilename the files module ModulePath will import from.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Target - Wrapper for Target specific information.
SubtargetFeatures - Manages the enabling and disabling of subtarget specific features.
StringRef str() const
Explicit conversion to StringRef.
LinkageTypes
An enumeration for the kinds of linkage for global values.
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
void collectDefinedGVSummariesPerModule(StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
std::unique_ptr< ModuleSummaryIndex > linkCombinedIndex()
Produce the combined summary index from all the bitcode files: "thin-link".
unsigned RelaxELFRelocations
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
static void gatherImportedSummariesForModule(StringRef ModulePath, ModuleSummaryIndex &Index, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the list of summaries needed for importing into module.
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
std::map< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module...
A raw_ostream that writes to a file descriptor.
size_type count(const ValueT &V) const
Return 1 if the specified key is in the set, 0 otherwise.
void WriteBitcodeToFile(const Module *M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false)
Write the specified module to the specified raw output stream.
void thinLTOResolveWeakForLinkerInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
Resolve Weak and LinkOnce values in the Index.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatileSize=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath)
Create a file in the system temporary directory.
DenseSet< GlobalValue::GUID > computeDeadSymbols(const ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of t...
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
iterator find(const KeyT &Val)
void preserveSymbol(StringRef Name)
Adds to a list of all global symbols that must exist in the final generated code. ...
void thinLTOResolveWeakForLinkerModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve WeakForLinker values in TheModule based on the information recorded in the summaries during g...
void crossModuleImport(Module &Module, ModuleSummaryIndex &Index)
Perform cross-module importing for the module identified by ModuleIdentifier.
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Optional< Reloc::Model > RelocModel
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef getBufferIdentifier() const
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
void internalize(Module &Module, ModuleSummaryIndex &Index)
Perform internalization.
The function importer is automatically importing function from other modules based on the provided su...
const FeatureBitset Features
CachePruning & setPruningInterval(std::chrono::seconds PruningInterval)
Define the pruning interval.
StringSet - A wrapper for StringMap that provides set-like functionality.
Primary interface to the complete machine description for the target machine.
static void emitImports(StringRef ModulePath, StringRef OutputName, ModuleSummaryIndex &Index)
Compute and emit the imported files for module at ModulePath.
void mergeFrom(std::unique_ptr< ModuleSummaryIndex > Other, uint64_t NextModuleId)
Add the given per-module index into this module index/summary, assigning it the given module ID...
StringRef - Represent a constant reference to a string, i.e.
bool exists(file_status status)
Does file exist?
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
bool AreStatisticsEnabled()
Check if statistics are enabled.
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
LLVMContext & getContext() const
Get the global data context.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Handle pruning a directory provided a path and some options to control what to prune.