46 errs() <<
"failed to open " << Path <<
": " << Msg <<
'\n';
52 bool UseInputModulePath) {
61 auto setHook = [&](std::string PathSuffix,
ModuleHookFn &Hook) {
64 Hook = [=](
unsigned Task,
const Module &M) {
67 if (LinkerHook && !LinkerHook(Task, M))
70 std::string PathPrefix;
74 if (M.getModuleIdentifier() ==
"ld-temp.o" || !UseInputModulePath) {
75 PathPrefix = OutputFileName +
utostr(Task);
77 PathPrefix = M.getModuleIdentifier();
78 std::string Path = PathPrefix +
"." + PathSuffix +
".bc";
98 std::string Path = OutputFileName +
"index.bc";
114 std::unique_ptr<TargetMachine>
119 for (
const std::string &
A : Conf.
MAttrs)
140 assert(PB.parseAAPipeline(AA,
"default"));
151 PB.registerModuleAnalyses(MAM);
152 PB.registerCGSCCAnalyses(CGAM);
153 PB.registerFunctionAnalyses(FAM);
154 PB.registerLoopAnalyses(LAM);
155 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
180 MPM = PB.buildThinLTODefaultPipeline(OL,
false );
182 MPM = PB.buildLTODefaultPipeline(OL,
false );
189 std::string PipelineDesc,
190 std::string AAPipelineDesc,
191 bool DisableVerify) {
196 if (!AAPipelineDesc.empty())
197 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
210 PB.registerModuleAnalyses(MAM);
211 PB.registerCGSCCAnalyses(CGAM);
212 PB.registerFunctionAnalyses(FAM);
213 PB.registerLoopAnalyses(LAM);
214 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
222 if (!PB.parsePassPipeline(MPM, PipelineDesc))
265 runNewPMPasses(Mod, TM, Conf.
OptLevel, IsThinLTO);
267 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
272 unsigned Task,
Module &Mod) {
276 auto Stream = AddStream(Task);
280 CodeGenPasses.
run(Mod);
284 unsigned ParallelCodeGenParallelismLevel,
285 std::unique_ptr<Module> Mod) {
286 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
287 unsigned ThreadCount = 0;
291 std::move(Mod), ParallelCodeGenParallelismLevel,
292 [&](std::unique_ptr<Module> MPart) {
304 CodegenThreadPool.async(
312 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.
get());
314 std::unique_ptr<TargetMachine> TM =
315 createTargetMachine(C, T, *MPartInCtx);
317 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
321 std::move(BC), ThreadCount++);
328 CodegenThreadPool.wait();
352 DiagOutputFile->keep();
353 DiagOutputFile->os().flush();
357 unsigned ParallelCodeGenParallelismLevel,
358 std::unique_ptr<Module> Mod,
364 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
370 return DiagFileOrErr.takeError();
371 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
374 if (!
opt(C, TM.get(), 0, *Mod,
false,
375 &CombinedIndex,
nullptr)) {
381 if (ParallelCodeGenParallelismLevel == 1) {
382 codegen(C, TM.get(), AddStream, 0, *Mod);
384 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
400 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
403 codegen(Conf, TM.get(), AddStream, Task, Mod);
417 if (!DefinedGlobals.
empty())
426 "ODR Type uniquing should be enabled on the context");
429 return I->second.getLazyModule(Mod.
getContext(),
441 if (!
opt(Conf, TM.get(), Task, Mod,
true,
442 nullptr, &CombinedIndex))
445 codegen(Conf, TM.get(), AddStream, Task, Mod);
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, TargetMachine::CodeGenFileType FileType)
Interfaces for registering analysis passes, producing common pass manager configurations, and parsing of pass pipelines.
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs...ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
CodeGenOpt::Level CGOptLevel
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
A Module instance is used to store all the information related to an LLVM module. ...
bool ShouldDiscardValueNames
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
void SplitModule(std::unique_ptr< Module > M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false)
Splits the module M into N linkable partitions.
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
ModuleSummaryIndex * ExportSummary
The module summary index to use for exporting information from the regular LTO phase, for example for the CFI and devirtualization type tests.
const ModuleSummaryIndex * ImportSummary
The module summary index to use for importing information to the thin LTO backends, for example for the CFI and devirtualization type tests.
A raw_ostream that writes to an SmallVector or SmallString.
OptimizationLevel
LLVM-provided high-level optimization levels.
Implementation of the target library information.
This class implements a map that also provides access to all stored values in a deterministic order...
std::string PGOSampleUse
Path of the sample Profile data file.
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.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Pass * Inliner
Inliner - Specifies the inliner to use.
CombinedIndexHookFn CombinedIndexHook
const Triple & getTargetTriple() const
std::function< std::unique_ptr< NativeObjectStream >unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
void add(Pass *P) override
Add a pass to the queue of passes to run.
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::vector< std::string > MAttrs
void populateLTOPassManager(legacy::PassManagerBase &PM)
This class provides access to building LLVM's passes.
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Tagged union holding either a T or a Error.
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
std::string SampleProfile
Sample PGO profile path.
static std::string utostr(uint64_t X, bool isNeg=false)
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
iterator find(const KeyT &Key)
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, CodeGenFileType, bool=true, AnalysisID=nullptr, AnalysisID=nullptr, AnalysisID=nullptr, AnalysisID=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
PassManager manages ModulePassManagers.
void WriteBitcodeToFile(const Module *M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Disable as many optimizations as possible.
A manager for alias analyses.
virtual TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
bool UseNewPM
Use the new pass manager.
Expected< std::unique_ptr< tool_output_file > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
Optimize for fast execution as much as possible.
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
cl::opt< Reloc::Model > RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::values(clEnumValN(Reloc::Static,"static","Non-relocatable code"), clEnumValN(Reloc::PIC_,"pic","Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC,"dynamic-no-pic","Relocatable external references, non-relocatable code"), clEnumValN(Reloc::ROPI,"ropi","Code and read-only data relocatable, accessed PC-relative"), clEnumValN(Reloc::RWPI,"rwpi","Read-write data relocatable, accessed relative to static base"), clEnumValN(Reloc::ROPI_RWPI,"ropi-rwpi","Combination of ropi and rwpi")))
std::string getString() const
Returns features as a string.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
TargetMachine::CodeGenFileType CGFileType
Triple - Helper class for working with autoconf configuration names.
std::string RemarksFilename
Optimization remarks file path.
static ErrorSuccess success()
Create a success value.
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
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...
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
#define LLVM_ATTRIBUTE_NORETURN
Optional< Reloc::Model > RelocModel
reference get()
Returns a reference to the stored T value.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Target - Wrapper for Target specific information.
Manages the enabling and disabling of subtarget specific features.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
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 ...
The file should be opened in text mode on platforms that make this distinction.
llvm_unreachable("Unknown RegBank!")
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
Error thinBackend(Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
A raw_ostream that writes to a file descriptor.
pointer data()
Return a pointer to the vector's buffer, even if empty().
Manages a sequence of passes over a particular unit of IR.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
void setTargetTriple(StringRef T)
Set the target triple.
CodeModel::Model CodeModel
void thinLTOResolveWeakForLinkerModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve WeakForLinker values in TheModule based on the information recorded in the summaries during g...
This header provides classes for managing passes over SCCs of the call graph.
LLVM_NODISCARD bool empty() const
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Error backend(Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Optimize quickly without destroying debuggability.
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
The function importer is automatically importing function from other modules based on the provided su...
Lightweight error class with error context and mandatory checking.
const FeatureBitset Features
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
const Target & getTarget() const
Primary interface to the complete machine description for the target machine.
Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false)
This is a convenience function that configures this Config object to write temporary files named afte...
A derived class of LLVMContext that initializes itself according to a given Config object...
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
static LLVM_ATTRIBUTE_NORETURN void reportOpenError(StringRef Path, Twine Msg)
This header defines various interfaces for pass management in LLVM.
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
std::unique_ptr< Module > splitCodeGen(std::unique_ptr< Module > M, ArrayRef< raw_pwrite_stream * > OSs, ArrayRef< llvm::raw_pwrite_stream * > BCOSs, const std::function< std::unique_ptr< TargetMachine >()> &TMFactory, TargetMachine::CodeGenFileType FT=TargetMachine::CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
static void finalizeOptimizationRemarks(std::unique_ptr< tool_output_file > DiagOutputFile)
LLVMContext & getContext() const
Get the global data context.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...