25 #include "llvm/Config/config.h" 62 #include <system_error> 66 #ifdef LLVM_VERSION_INFO 67 return PACKAGE_NAME
" version " PACKAGE_VERSION
", " LLVM_VERSION_INFO;
69 return PACKAGE_NAME
" version " PACKAGE_VERSION;
75 "lto-discard-value-names",
76 cl::desc(
"Strip names from Value during LTO (other than GlobalValue)."),
86 cl::desc(
"Output filename for pass remarks"),
90 "lto-pass-remarks-with-hotness",
91 cl::desc(
"With PGO, include profile count in optimization remarks"),
96 : Context(Context), MergedModule(new
Module(
"ld-temp.o", Context)),
97 TheLinker(new
Linker(*MergedModule)) {
100 initializeLTOPasses();
108 void LTOCodeGenerator::initializeLTOPasses() {
136 for (
int i = 0, e = undefs.size(); i != e; ++i)
137 AsmUndefinedRefs[undefs[i]] = 1;
142 "Expected module in same context");
144 bool ret = TheLinker->linkInModule(Mod->
takeModule());
148 HasVerifiedInput =
false;
154 assert(&Mod->getModule().getContext() == &Context &&
155 "Expected module in same context");
157 AsmUndefinedRefs.
clear();
159 MergedModule = Mod->takeModule();
160 TheLinker = make_unique<Linker>(*MergedModule);
164 HasVerifiedInput =
false;
168 this->Options = Options;
174 EmitDwarfDebugInfo =
false;
178 EmitDwarfDebugInfo =
true;
204 if (!determineTarget())
208 verifyMergedModuleOnce();
211 applyScopeRestrictions();
217 std::string ErrMsg =
"could not open bitcode file for writing: ";
218 ErrMsg += Path.
str() +
": " + EC.message();
228 std::string ErrMsg =
"could not write bitcode file: ";
229 ErrMsg += Path.
str() +
": " + Out.
os().
error().message();
239 bool LTOCodeGenerator::compileOptimizedToFile(
const char **
Name) {
250 emitError(EC.message());
260 emitError((
Twine(
"could not write object file: ") + Filename +
": " +
261 objFile.
os().
error().message())
274 NativeObjectPath = Filename.
c_str();
275 *Name = NativeObjectPath.c_str();
279 std::unique_ptr<MemoryBuffer>
282 if (!compileOptimizedToFile(&name))
288 if (std::error_code EC = BufferOrErr.
getError()) {
289 emitError(EC.message());
297 return std::move(*BufferOrErr);
302 bool DisableGVNLoadPRE,
303 bool DisableVectorization) {
304 if (!
optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
305 DisableVectorization))
308 return compileOptimizedToFile(Name);
311 std::unique_ptr<MemoryBuffer>
313 bool DisableGVNLoadPRE,
bool DisableVectorization) {
314 if (!
optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
315 DisableVectorization))
321 bool LTOCodeGenerator::determineTarget() {
325 TripleStr = MergedModule->getTargetTriple();
326 if (TripleStr.empty()) {
328 MergedModule->setTargetTriple(TripleStr);
355 TargetMach = createTargetMachine();
359 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
361 TripleStr, MCpu, FeatureStr, Options, RelocModel,
None, CGOptLevel));
367 void LTOCodeGenerator::preserveDiscardableGVs(
370 std::vector<GlobalValue *> Used;
372 if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
375 if (GV.hasAvailableExternallyLinkage())
377 (
Twine(
"Linker asked to preserve available_externally global: '") +
378 GV.getName() +
"'").str());
379 if (GV.hasInternalLinkage())
380 return emitWarning((
Twine(
"Linker asked to preserve internal global: '") +
381 GV.getName() +
"'").str());
384 for (
auto &GV : TheModule)
385 mayPreserveGlobal(GV);
386 for (
auto &GV : TheModule.globals())
387 mayPreserveGlobal(GV);
388 for (
auto &GV : TheModule.aliases())
389 mayPreserveGlobal(GV);
397 void LTOCodeGenerator::applyScopeRestrictions() {
398 if (ScopeRestrictionsDone)
414 MangledName.
reserve(GV.getName().size() + 1);
416 return MustPreserveSymbols.
count(MangledName);
422 if (!ShouldInternalize)
425 if (ShouldRestoreGlobalsLinkage) {
430 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
432 ExternalSymbols.
insert(std::make_pair(GV.getName(), GV.getLinkage()));
434 for (
auto &GV : *MergedModule)
436 for (
auto &GV : MergedModule->globals())
438 for (
auto &GV : MergedModule->aliases())
448 ScopeRestrictionsDone =
true;
452 void LTOCodeGenerator::restoreLinkageForExternals() {
453 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
456 assert(ScopeRestrictionsDone &&
457 "Cannot externalize without internalization!");
459 if (ExternalSymbols.
empty())
463 if (!GV.hasLocalLinkage() || !GV.hasName())
466 auto I = ExternalSymbols.
find(GV.getName());
467 if (
I == ExternalSymbols.
end())
470 GV.setLinkage(
I->second);
478 void LTOCodeGenerator::verifyMergedModuleOnce() {
480 if (HasVerifiedInput)
482 HasVerifiedInput =
true;
484 bool BrokenDebugInfo =
false;
487 if (BrokenDebugInfo) {
488 emitWarning(
"Invalid debug info found, debug info will be stripped");
493 void LTOCodeGenerator::finishOptimizationRemarks() {
494 if (DiagnosticOutputFile) {
495 DiagnosticOutputFile->keep();
497 DiagnosticOutputFile->os().flush();
503 bool DisableGVNLoadPRE,
504 bool DisableVectorization) {
505 if (!this->determineTarget())
510 if (!DiagFileOrErr) {
511 errs() <<
"Error: " <<
toString(DiagFileOrErr.takeError()) <<
"\n";
514 DiagnosticOutputFile = std::move(*DiagFileOrErr);
518 verifyMergedModuleOnce();
521 this->applyScopeRestrictions();
527 MergedModule->setDataLayout(TargetMach->createDataLayout());
532 Triple TargetTriple(TargetMach->getTargetTriple());
535 PMB.LoopVectorize = !DisableVectorization;
536 PMB.SLPVectorize = !DisableVectorization;
541 PMB.LibraryInfo->disableAllFunctions();
542 PMB.OptLevel = OptLevel;
543 PMB.VerifyInput = !DisableVerify;
544 PMB.VerifyOutput = !DisableVerify;
546 PMB.populateLTOPassManager(passes);
549 passes.
run(*MergedModule);
555 if (!this->determineTarget())
560 verifyMergedModuleOnce();
567 preCodeGenPasses.
run(*MergedModule);
571 restoreLinkageForExternals();
578 MergedModule =
splitCodeGen(std::move(MergedModule), Out, {},
579 [&]() {
return createTargetMachine(); }, FileType,
580 ShouldRestoreGlobalsLinkage);
587 finishOptimizationRemarks();
595 for (std::pair<StringRef, StringRef> o =
getToken(Options); !o.first.empty();
597 CodegenOptions.push_back(o.first);
602 if (!CodegenOptions.empty()) {
604 std::vector<const char *> CodegenArgv(1,
"libLLVMLTO");
605 for (std::string &
Arg : CodegenOptions)
606 CodegenArgv.push_back(
Arg.c_str());
630 std::string MsgStorage;
638 assert(DiagHandler &&
"Invalid diagnostic handler");
639 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
646 : CodeGenerator(CodeGenPtr) {}
648 CodeGenerator->DiagnosticHandler(DI);
657 this->DiagHandler = DiagHandler;
658 this->DiagContext = Ctxt;
677 void LTOCodeGenerator::emitError(
const std::string &ErrMsg) {
679 (*DiagHandler)(
LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
684 void LTOCodeGenerator::emitWarning(
const std::string &ErrMsg) {
void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
void initializeDCELegacyPassPass(PassRegistry &)
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
This is the base class for diagnostic handling in LLVM.
void initializeGlobalOptLegacyPassPass(PassRegistry &)
Represents either an error or a value T.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
void initializeInternalizeLegacyPassPass(PassRegistry &)
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
std::unique_ptr< MemoryBuffer > compileOptimized()
Compiles the merged optimized module into a single output file.
A Module instance is used to store all the information related to an LLVM module. ...
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM=None, CodeGenOpt::Level OL=CodeGenOpt::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
void initializeSimpleInlinerPass(PassRegistry &)
void initializeJumpThreadingPass(PassRegistry &)
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
lto_codegen_diagnostic_severity_t
Diagnostic severity.
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
void enableDebugTypeODRUniquing()
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
std::string getString() const
Returns features as a string.
const FeatureBitset Features
An efficient, type-erasing, non-owning reference to a callable.
void initializeGlobalDCELegacyPassPass(PassRegistry &)
iterator find(StringRef Key)
bool addModule(struct LTOModule *)
Merge given module.
Implementation of the target library information.
bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Optimizes the merged module.
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 FileType=TargetMachine::CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void reserve(size_type N)
void reportAndResetTimings()
If -time-passes has been specified, report the timings immediately and then reset the timers to zero...
std::unique_ptr< Module > takeModule()
std::error_code error() const
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
void initializeReversePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
static void externalize(GlobalValue *GV)
void initializePruneEHPass(PassRegistry &)
amdgpu Simplify well known AMD library false Value Value const Twine & Name
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.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVMContext & getContext() const
Get the global data context.
void initializeArgPromotionPass(PassRegistry &)
std::unique_ptr< MemoryBuffer > compile(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
As with compile_to_file(), this function compiles the merged module into single output file...
Interface for custom diagnostic printing.
This header defines classes/functions to handle pass execution timing information with interfaces for...
bool writeMergedModules(StringRef Path)
Write the merged module to the file specified by the given path.
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \\\)
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Pass * createObjCARCContractPass()
static const char * getVersionString()
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
This class provides the core functionality of linking in LLVM.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void initializeGVNLegacyPassPass(PassRegistry &)
PassManager manages ModulePassManagers.
initializer< Ty > init(const Ty &Val)
This is the base abstract class for diagnostic reporting in the backend.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
This is an important class for using LLVM in a threaded context.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::error_code getError() const
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.
void initializeSROALegacyPassPass(PassRegistry &)
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, const char *EnvVar=nullptr)
void setOptLevel(unsigned OptLevel)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
void setTargetOptions(const TargetOptions &Options)
const Module & getModule() const
C++ class which implements the opaque lto_module_t type.
void setCodeGenDebugOptions(StringRef Opts)
Pass options to the driver and optimization passes.
void initializeMemCpyOptLegacyPassPass(PassRegistry &)
void initializeConstantMergeLegacyPassPass(PassRegistry &)
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
C++ class which implements the opaque lto_code_gen_t type.
void initializeGlobalsAAWrapperPassPass(PassRegistry &)
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
const std::vector< StringRef > & getAsmUndefinedRefs()
Module.h This file contains the declarations for the Module class.
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
Manages the enabling and disabling of subtarget specific features.
void initializeDAHPass(PassRegistry &)
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
amdgpu Simplify well known AMD library false Value Value * Arg
Basic diagnostic printer that uses an underlying raw_ostream.
void DiagnosticHandler(const DiagnosticInfo &DI)
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath)
Create a file in the system temporary directory.
void initializePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
void initializeIPSCCPLegacyPassPass(PassRegistry &)
bool compile_to_file(const char **Name, bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Compile the merged module into a single output file; the path to output file is returned to the calle...
DiagnosticSeverity getSeverity() const
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void initializeInstructionCombiningPassPass(PassRegistry &)
void close()
Manually flush the stream and close the file.
void updateCompilerUsed(Module &TheModule, const TargetMachine &TM, const StringSet<> &AsmUndefinedRefs)
Find all globals in TheModule that are referenced in AsmUndefinedRefs, as well as the user-supplied f...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
void setAsmUndefinedRefs(struct LTOModule *)
void initializeCFGSimplifyPassPass(PassRegistry &)
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
LTOCodeGenerator(LLVMContext &Context)
static cl::opt< bool, true > Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag))
void initializeLegacyLICMPassPass(PassRegistry &)
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
StringRef - Represent a constant reference to a string, i.e.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
void parseCodeGenDebugOptions()
Parse the options set in setCodeGenDebugOptions.
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
void setModule(std::unique_ptr< LTOModule > M)
Set the destination module.
void initializeMergedLoadStoreMotionLegacyPassPass(PassRegistry &)
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV, CallGraph *CG=nullptr)
Helper function to internalize functions and variables in a Module.
bool AreStatisticsEnabled()
Check if statistics are enabled.
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
void clear_error()
Set the flag read by has_error() to false.
void setDebugInfo(lto_debug_model)