LLVM  14.0.0git
LTOCodeGenerator.h
Go to the documentation of this file.
1 //===-LTOCodeGenerator.h - LLVM Link Time Optimizer -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the LTOCodeGenerator class.
10 //
11 // LTO compilation consists of three phases: Pre-IPO, IPO and Post-IPO.
12 //
13 // The Pre-IPO phase compiles source code into bitcode file. The resulting
14 // bitcode files, along with object files and libraries, will be fed to the
15 // linker to through the IPO and Post-IPO phases. By using obj-file extension,
16 // the resulting bitcode file disguises itself as an object file, and therefore
17 // obviates the need of writing a special set of the make-rules only for LTO
18 // compilation.
19 //
20 // The IPO phase perform inter-procedural analyses and optimizations, and
21 // the Post-IPO consists two sub-phases: intra-procedural scalar optimizations
22 // (SOPT), and intra-procedural target-dependent code generator (CG).
23 //
24 // As of this writing, we don't separate IPO and the Post-IPO SOPT. They
25 // are intermingled together, and are driven by a single pass manager (see
26 // PassManagerBuilder::populateLTOPassManager()).
27 //
28 // The "LTOCodeGenerator" is the driver for the IPO and Post-IPO stages.
29 // The "CodeGenerator" here is bit confusing. Don't confuse the "CodeGenerator"
30 // with the machine specific code generator.
31 //
32 //===----------------------------------------------------------------------===//
33 
34 #ifndef LLVM_LTO_LEGACY_LTOCODEGENERATOR_H
35 #define LLVM_LTO_LEGACY_LTOCODEGENERATOR_H
36 
37 #include "llvm-c/lto.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/StringMap.h"
41 #include "llvm/ADT/StringSet.h"
42 #include "llvm/IR/GlobalValue.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/LTO/Config.h"
45 #include "llvm/LTO/LTO.h"
47 #include "llvm/Support/Error.h"
51 #include <string>
52 #include <vector>
53 
54 /// Enable global value internalization in LTO.
56 
57 namespace llvm {
58 template <typename T> class ArrayRef;
59  class LLVMContext;
60  class DiagnosticInfo;
61  class Linker;
62  class Mangler;
63  class MemoryBuffer;
64  class TargetLibraryInfo;
65  class TargetMachine;
66  class raw_ostream;
67  class raw_pwrite_stream;
68 
69 //===----------------------------------------------------------------------===//
70 /// C++ class which implements the opaque lto_code_gen_t type.
71 ///
73  static const char *getVersionString();
74 
75  LTOCodeGenerator(LLVMContext &Context);
77 
78  /// Merge given module. Return true on success.
79  ///
80  /// Resets \a HasVerifiedInput.
81  bool addModule(struct LTOModule *);
82 
83  /// Set the destination module.
84  ///
85  /// Resets \a HasVerifiedInput.
86  void setModule(std::unique_ptr<LTOModule> M);
87 
88  void setAsmUndefinedRefs(struct LTOModule *);
92  Config.RelocModel = Model;
93  }
94 
95  /// Set the file type to be emitted (assembly or object code).
96  /// The default is CGFT_ObjectFile.
97  void setFileType(CodeGenFileType FT) { Config.CGFileType = FT; }
98 
99  void setCpu(StringRef MCpu) { Config.CPU = std::string(MCpu); }
100  void setAttrs(std::vector<std::string> MAttrs) { Config.MAttrs = MAttrs; }
101  void setOptLevel(unsigned OptLevel);
102 
103  void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
104  void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }
105 
106  /// Restore linkage of globals
107  ///
108  /// When set, the linkage of globals will be restored prior to code
109  /// generation. That is, a global symbol that had external linkage prior to
110  /// LTO will be emitted with external linkage again; and a local will remain
111  /// local. Note that this option only affects the end result - globals may
112  /// still be internalized in the process of LTO and may be modified and/or
113  /// deleted where legal.
114  ///
115  /// The default behavior will internalize globals (unless on the preserve
116  /// list) and, if parallel code generation is enabled, will externalize
117  /// all locals.
119  ShouldRestoreGlobalsLinkage = Value;
120  }
121 
122  void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols.insert(Sym); }
123 
124  /// Pass options to the driver and optimization passes.
125  ///
126  /// These options are not necessarily for debugging purpose (the function
127  /// name is misleading). This function should be called before
128  /// LTOCodeGenerator::compilexxx(), and
129  /// LTOCodeGenerator::writeMergedModules().
131 
132  /// Parse the options set in setCodeGenDebugOptions.
133  ///
134  /// Like \a setCodeGenDebugOptions(), this must be called before
135  /// LTOCodeGenerator::compilexxx() and
136  /// LTOCodeGenerator::writeMergedModules().
138 
139  /// Write the merged module to the file specified by the given path. Return
140  /// true on success.
141  ///
142  /// Calls \a verifyMergedModuleOnce().
143  bool writeMergedModules(StringRef Path);
144 
145  /// Compile the merged module into a *single* output file; the path to output
146  /// file is returned to the caller via argument "name". Return true on
147  /// success.
148  ///
149  /// \note It is up to the linker to remove the intermediate output file. Do
150  /// not try to remove the object file in LTOCodeGenerator's destructor as we
151  /// don't who (LTOCodeGenerator or the output file) will last longer.
152  bool compile_to_file(const char **Name);
153 
154  /// As with compile_to_file(), this function compiles the merged module into
155  /// single output file. Instead of returning the output file path to the
156  /// caller (linker), it brings the output to a buffer, and returns the buffer
157  /// to the caller. This function should delete the intermediate file once
158  /// its content is brought to memory. Return NULL if the compilation was not
159  /// successful.
160  std::unique_ptr<MemoryBuffer> compile();
161 
162  /// Optimizes the merged module. Returns true on success.
163  ///
164  /// Calls \a verifyMergedModuleOnce().
165  bool optimize();
166 
167  /// Compiles the merged optimized module into a single output file. It brings
168  /// the output to a buffer, and returns the buffer to the caller. Return NULL
169  /// if the compilation was not successful.
170  std::unique_ptr<MemoryBuffer> compileOptimized();
171 
172  /// Compile the merged optimized module \p ParallelismLevel output files each
173  /// representing a linkable partition of the module. If out contains more
174  /// than one element, code generation is done in parallel with \p
175  /// ParallelismLevel threads. Output files will be written to the streams
176  /// created using the \p AddStream callback. Returns true on success.
177  ///
178  /// Calls \a verifyMergedModuleOnce().
179  bool compileOptimized(AddStreamFn AddStream, unsigned ParallelismLevel);
180 
181  /// Enable the Freestanding mode: indicate that the optimizer should not
182  /// assume builtins are present on the target.
183  void setFreestanding(bool Enabled) { Config.Freestanding = Enabled; }
184 
185  void setDisableVerify(bool Value) { Config.DisableVerify = Value; }
186 
187  void setUseNewPM(bool Value) { Config.UseNewPM = Value; }
188 
190 
192 
193  void resetMergedModule() { MergedModule.reset(); }
194  void DiagnosticHandler(const DiagnosticInfo &DI);
195 
196 private:
197  /// Verify the merged module on first call.
198  ///
199  /// Sets \a HasVerifiedInput on first call and doesn't run again on the same
200  /// input.
201  void verifyMergedModuleOnce();
202 
203  bool compileOptimizedToFile(const char **Name);
204  void restoreLinkageForExternals();
205  void applyScopeRestrictions();
206  void preserveDiscardableGVs(
207  Module &TheModule,
209 
210  bool determineTarget();
211  std::unique_ptr<TargetMachine> createTargetMachine();
212 
213  void emitError(const std::string &ErrMsg);
214  void emitWarning(const std::string &ErrMsg);
215 
216  void finishOptimizationRemarks();
217 
219  std::unique_ptr<Module> MergedModule;
220  std::unique_ptr<Linker> TheLinker;
221  std::unique_ptr<TargetMachine> TargetMach;
222  bool EmitDwarfDebugInfo = false;
223  bool ScopeRestrictionsDone = false;
224  bool HasVerifiedInput = false;
225  StringSet<> MustPreserveSymbols;
226  StringSet<> AsmUndefinedRefs;
227  StringMap<GlobalValue::LinkageTypes> ExternalSymbols;
228  std::vector<std::string> CodegenOptions;
229  std::string FeatureStr;
230  std::string NativeObjectPath;
231  const Target *MArch = nullptr;
232  std::string TripleStr;
233  lto_diagnostic_handler_t DiagHandler = nullptr;
234  void *DiagContext = nullptr;
235  bool ShouldInternalize = EnableLTOInternalization;
236  bool ShouldEmbedUselists = false;
237  bool ShouldRestoreGlobalsLinkage = false;
238  std::unique_ptr<ToolOutputFile> DiagnosticOutputFile;
239  std::unique_ptr<ToolOutputFile> StatsFile = nullptr;
240 
241  lto::Config Config;
242 };
243 
244 /// A convenience function that calls cl::ParseCommandLineOptions on the given
245 /// set of options.
246 void parseCommandLineOptions(std::vector<std::string> &Options);
247 }
248 #endif
llvm::LTOCodeGenerator::getContext
LLVMContext & getContext()
Definition: LTOCodeGenerator.h:191
llvm::LTOCodeGenerator::setCodeGenDebugOptions
void setCodeGenDebugOptions(ArrayRef< StringRef > Opts)
Pass options to the driver and optimization passes.
Definition: LTOCodeGenerator.cpp:594
llvm::LTOCodeGenerator::setDiagnosticHandler
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
Definition: LTOCodeGenerator.cpp:657
llvm
This file implements support for optimizing divisions by a constant.
Definition: AllocatorList.h:23
mustPreserveGV
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
Definition: AMDGPUTargetMachine.cpp:524
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::LTOCodeGenerator::parseCodeGenDebugOptions
void parseCodeGenDebugOptions()
Parse the options set in setCodeGenDebugOptions.
Definition: LTOCodeGenerator.cpp:599
llvm::TargetOptions
Definition: TargetOptions.h:124
llvm::lto::Config::DisableVerify
bool DisableVerify
Definition: Config.h:58
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:137
llvm::LTOCodeGenerator::LTOCodeGenerator
LTOCodeGenerator(LLVMContext &Context)
Definition: LTOCodeGenerator.cpp:122
Error.h
llvm::LTOCodeGenerator::setDebugInfo
void setDebugInfo(lto_debug_model)
Definition: LTOCodeGenerator.cpp:174
llvm::LTOCodeGenerator::setTargetOptions
void setTargetOptions(const TargetOptions &Options)
Definition: LTOCodeGenerator.cpp:170
Module.h
llvm::lto::Config
LTO configuration.
Definition: Config.h:40
llvm::Optional< Reloc::Model >
llvm::lto::Config::Freestanding
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition: Config.h:65
llvm::LTOCodeGenerator::compile_to_file
bool compile_to_file(const char **Name)
Compile the merged module into a single output file; the path to output file is returned to the calle...
Definition: LTOCodeGenerator.cpp:301
llvm::LTOCodeGenerator::setShouldEmbedUselists
void setShouldEmbedUselists(bool Value)
Definition: LTOCodeGenerator.h:104
llvm::StringSet::insert
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:33
llvm::LTOCodeGenerator::setOptLevel
void setOptLevel(unsigned OptLevel)
Definition: LTOCodeGenerator.cpp:187
llvm::LTOCodeGenerator::addModule
bool addModule(struct LTOModule *)
Merge given module.
Definition: LTOCodeGenerator.cpp:143
llvm::Reloc::Model
Model
Definition: CodeGen.h:22
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
CommandLine.h
GlobalValue.h
llvm::LTOCodeGenerator::compile
std::unique_ptr< MemoryBuffer > compile()
As with compile_to_file(), this function compiles the merged module into single output file.
Definition: LTOCodeGenerator.cpp:308
TargetMachine.h
llvm::LTOCodeGenerator::setCodePICModel
void setCodePICModel(Optional< Reloc::Model > Model)
Definition: LTOCodeGenerator.h:91
llvm::LTOCodeGenerator::compileOptimized
std::unique_ptr< MemoryBuffer > compileOptimized()
Compiles the merged optimized module into a single output file.
Definition: LTOCodeGenerator.cpp:281
Options
const char LLVMTargetMachineRef LLVMPassBuilderOptionsRef Options
Definition: PassBuilderBindings.cpp:48
SmallPtrSet.h
llvm::LTOCodeGenerator::optimize
bool optimize()
Optimizes the merged module.
Definition: LTOCodeGenerator.cpp:503
llvm::DiagnosticInfo
This is the base abstract class for diagnostic reporting in the backend.
Definition: DiagnosticInfo.h:103
StringMap.h
llvm::LTOCodeGenerator::setAttrs
void setAttrs(std::vector< std::string > MAttrs)
Definition: LTOCodeGenerator.h:100
lto.h
llvm::LTOCodeGenerator::setShouldInternalize
void setShouldInternalize(bool Value)
Definition: LTOCodeGenerator.h:103
lto_debug_model
lto_debug_model
Definition: lto.h:79
llvm::StringMap< GlobalValue::LinkageTypes >
llvm::LTOCodeGenerator::DiagnosticHandler
void DiagnosticHandler(const DiagnosticInfo &DI)
Definition: LTOCodeGenerator.cpp:614
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:168
llvm::LTOCodeGenerator::getVersionString
static const char * getVersionString()
Definition: LTOCodeGenerator.cpp:68
llvm::cl::opt< bool >
llvm::parseCommandLineOptions
void parseCommandLineOptions(std::vector< std::string > &Options)
A convenience function that calls cl::ParseCommandLineOptions on the given set of options.
Definition: LTOCodeGenerator.cpp:604
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::LTOCodeGenerator::~LTOCodeGenerator
~LTOCodeGenerator()
Definition: LTOCodeGenerator.cpp:135
llvm::LTOCodeGenerator::setDisableVerify
void setDisableVerify(bool Value)
Definition: LTOCodeGenerator.h:185
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
llvm::LTOCodeGenerator
C++ class which implements the opaque lto_code_gen_t type.
Definition: LTOCodeGenerator.h:72
llvm::LTOCodeGenerator::setFileType
void setFileType(CodeGenFileType FT)
Set the file type to be emitted (assembly or object code).
Definition: LTOCodeGenerator.h:97
ArrayRef.h
ToolOutputFile.h
lto_diagnostic_handler_t
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition: lto.h:346
llvm::lto::Config::MAttrs
std::vector< std::string > MAttrs
Definition: Config.h:49
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
TargetOptions.h
llvm::StringSet
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:22
llvm::LTOCodeGenerator::setModule
void setModule(std::unique_ptr< LTOModule > M)
Set the destination module.
Definition: LTOCodeGenerator.cpp:156
llvm::lto::Config::RelocModel
Optional< Reloc::Model > RelocModel
Definition: Config.h:53
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: APInt.h:32
llvm::CodeGenFileType
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:63
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
Config.h
llvm::LTOCodeGenerator::addMustPreserveSymbol
void addMustPreserveSymbol(StringRef Sym)
Definition: LTOCodeGenerator.h:122
llvm::LTOCodeGenerator::resetMergedModule
void resetMergedModule()
Definition: LTOCodeGenerator.h:193
llvm::AddStreamFn
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.
Definition: Caching.h:41
StringSet.h
llvm::LTOCodeGenerator::writeMergedModules
bool writeMergedModules(StringRef Path)
Write the merged module to the file specified by the given path.
Definition: LTOCodeGenerator.cpp:208
llvm::LTOCodeGenerator::setFreestanding
void setFreestanding(bool Enabled)
Enable the Freestanding mode: indicate that the optimizer should not assume builtins are present on t...
Definition: LTOCodeGenerator.h:183
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:52
Enabled
static bool Enabled
Definition: Statistic.cpp:46
llvm::TargetStackID::Value
Value
Definition: TargetFrameLowering.h:27
EnableLTOInternalization
llvm::cl::opt< bool > EnableLTOInternalization
Enable global value internalization in LTO.
llvm::lto::Config::CGFileType
CodeGenFileType CGFileType
Definition: Config.h:56
llvm::lto::Config::UseNewPM
bool UseNewPM
Use the new pass manager.
Definition: Config.h:61
LTO.h
llvm::LTOCodeGenerator::setCpu
void setCpu(StringRef MCpu)
Definition: LTOCodeGenerator.h:99
llvm::LTOCodeGenerator::setShouldRestoreGlobalsLinkage
void setShouldRestoreGlobalsLinkage(bool Value)
Restore linkage of globals.
Definition: LTOCodeGenerator.h:118
llvm::LTOCodeGenerator::setUseNewPM
void setUseNewPM(bool Value)
Definition: LTOCodeGenerator.h:187
llvm::lto::Config::CPU
std::string CPU
Definition: Config.h:47
llvm::LTOCodeGenerator::setAsmUndefinedRefs
void setAsmUndefinedRefs(struct LTOModule *)
Definition: LTOCodeGenerator.cpp:137
llvm::LTOModule
C++ class which implements the opaque lto_module_t type.
Definition: LTOModule.h:38
llvm::Value
LLVM Value Representation.
Definition: Value.h:74