LLVM 24.0.0git
Config.h
Go to the documentation of this file.
1//===-Config.h - LLVM Link Time Optimizer Configuration ---------*- C++ -*-===//
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 defines the lto::Config data structure, which allows clients to
10// configure LTO.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LTO_CONFIG_H
15#define LLVM_LTO_CONFIG_H
16
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/Config/llvm-config.h"
20#include "llvm/IR/GlobalValue.h"
21#include "llvm/IR/LLVMContext.h"
28
29#include <functional>
30#include <optional>
31
32namespace llvm {
33
34class Error;
35class Module;
38class PassPlugin;
39
40namespace lto {
41
42/// LTO configuration. A linker can configure LTO by setting fields in this data
43/// structure and passing it to the lto::LTO constructor.
44struct Config {
49 // The library options of every LLVMContext that LTO creates.
50 // TODO: Make it non-null once every client sets it. Null means the defaults.
52 // Note: when adding fields here, consider whether they need to be added to
53 // computeLTOCacheKey in LTO.cpp.
54 std::string CPU;
56 std::vector<std::string> MAttrs;
57 std::vector<std::string> MllvmArgs;
58 // Pass-plugins already loaded by the client. LTO does not take ownership, so
59 // they must outlive the lto::LTO object.
60 std::vector<llvm::PassPlugin *> LoadedPassPlugins;
61 // Plugins that are passed by filename are loaded in lto::LTO::run(). Clients
62 // that call lto::backend(), lto::thinBackend() or lto::opt() directly must
63 // use LoadedPassPlugins.
64 std::vector<std::string> PassPluginFilenames;
65 // "<plugin>,<arg>" values that lto::LTO::run() passes to pass plugins.
66 std::vector<std::string> PassPluginArgs;
67 std::function<void(PassBuilder &)> PassBuilderCallback;
68 std::optional<Reloc::Model> RelocModel = Reloc::PIC_;
69 std::optional<CodeModel::Model> CodeModel;
72 unsigned OptLevel = 2;
73 bool VerifyEach = false;
74 bool DisableVerify = false;
75
76 /// Flag to indicate that the optimizer should not assume builtins are present
77 /// on the target.
78 bool Freestanding = false;
79
80 /// Disable entirely the optimizer, including importing for ThinLTO
81 bool CodeGenOnly = false;
82
83 /// Run PGO context sensitive IR instrumentation.
84 bool RunCSIRInstr = false;
85
86 /// Turn on/off the warning about a hash mismatch in the PGO profile data.
87 bool PGOWarnMismatch = true;
88
89 /// Asserts whether we can assume whole program visibility during the LTO
90 /// link.
92
93 /// We're validating that all native vtables have corresponding type infos.
95 /// If all native vtables have corresponding type infos, allow
96 /// usage of RTTI to block devirtualization on types used in native files.
98
99 /// Always emit a Regular LTO object even when it is empty because no Regular
100 /// LTO modules were linked. This option is useful for some build system which
101 /// want to know a priori all possible output files.
103
104 /// If true, the LTO instance creates copies of the symbol names for LTO::run.
105 /// The lld linker uses string saver to keep symbol names alive and doesn't
106 /// need to create copies, so it can set this field to false.
108
109 /// This flag is used as one of parameters to calculate cache entries and to
110 /// ensure that in-process cache and out-of-process (DTLTO) cache are
111 /// distinguished.
112 mutable bool Dtlto = 0;
113
114 /// Allows non-imported definitions to get the potentially more constraining
115 /// visibility from the prevailing definition. FromPrevailing is the default
116 /// because it works for many binary formats. ELF can use the more optimized
117 /// 'ELF' scheme.
119
120 /// If this field is set, the set of passes run in the middle-end optimizer
121 /// will be the one specified by the string. Only works with the new pass
122 /// manager as the old one doesn't have this ability.
123 std::string OptPipeline;
124
125 // If this field is set, it has the same effect of specifying an AA pipeline
126 // identified by the string. Only works with the new pass manager, in
127 // conjunction OptPipeline.
128 std::string AAPipeline;
129
130 /// Setting this field will replace target triples in input files with this
131 /// triple.
132 std::string OverrideTriple;
133
134 /// Setting this field will replace unspecified target triples in input files
135 /// with this triple.
136 std::string DefaultTriple;
137
138 /// Context Sensitive PGO profile path.
139 std::string CSIRProfile;
140
141 /// Sample PGO profile path.
142 std::string SampleProfile;
143
144 /// Name remapping file for profile data.
145 std::string ProfileRemapping;
146
147 /// The directory to store .dwo files.
148 std::string DwoDir;
149
150 /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
151 /// attribute in the skeleton CU. This should generally only be used when
152 /// running an individual backend directly via thinBackend(), as otherwise
153 /// all objects would use the same .dwo file. Not used as output path.
154 std::string SplitDwarfFile;
155
156 /// The path to write a .dwo file to. This should generally only be used when
157 /// running an individual backend directly via thinBackend(), as otherwise
158 /// all .dwo files will be written to the same path. Not used in skeleton CU.
159 std::string SplitDwarfOutput;
160
161 /// Optimization remarks file path.
162 std::string RemarksFilename;
163
164 /// Optimization remarks pass filter.
165 std::string RemarksPasses;
166
167 /// Whether to emit optimization remarks with hotness informations.
168 bool RemarksWithHotness = false;
169
170 /// The minimum hotness value a diagnostic needs in order to be included in
171 /// optimization diagnostics.
172 ///
173 /// The threshold is an Optional value, which maps to one of the 3 states:
174 /// 1. 0 => threshold disabled. All emarks will be printed.
175 /// 2. positive int => manual threshold by user. Remarks with hotness exceed
176 /// threshold will be printed.
177 /// 3. None => 'auto' threshold by user. The actual value is not
178 /// available at command line, but will be synced with
179 /// hotness threhold from profile summary during
180 /// compilation.
181 ///
182 /// If threshold option is not specified, it is disabled by default.
183 std::optional<uint64_t> RemarksHotnessThreshold = 0;
184
185 /// The format used for serializing remarks (default: YAML).
186 std::string RemarksFormat;
187
188 /// Whether to emit the pass manager debuggging informations.
189 bool DebugPassManager = false;
190
191 /// Statistics output file path.
192 std::string StatsFile;
193
194 /// Specific thinLTO modules to compile.
195 std::vector<std::string> ThinLTOModulesToCompile;
196
197 /// Time trace enabled.
198 bool TimeTraceEnabled = false;
199
200 /// Time trace granularity.
201 unsigned TimeTraceGranularity = 500;
202
205
206 /// Add FSAFDO discriminators.
207 bool AddFSDiscriminator = false;
208
209 /// If this field is set, LTO will write input file paths and symbol
210 /// resolutions here in llvm-lto2 command line flag format. This can be
211 /// used for testing and for running the LTO pipeline outside of the linker
212 /// with llvm-lto2.
213 std::unique_ptr<raw_ostream> ResolutionFile;
214
215 /// Tunable parameters for passes in the default pipelines.
217
218 /// The following callbacks deal with tasks, which normally represent the
219 /// entire optimization and code generation pipeline for what will become a
220 /// single native object file. Each task has a unique identifier between 0 and
221 /// getMaxTasks()-1, which is supplied to the callback via the Task parameter.
222 /// A task represents the entire pipeline for ThinLTO and regular
223 /// (non-parallel) LTO, but a parallel code generation task will be split into
224 /// N tasks before code generation, where N is the parallelism level.
225 ///
226 /// LTO may decide to stop processing a task at any time, for example if the
227 /// module is empty or if a module hook (see below) returns false. For this
228 /// reason, the client should not expect to receive exactly getMaxTasks()
229 /// native object files.
230
231 /// A module hook may be used by a linker to perform actions during the LTO
232 /// pipeline. For example, a linker may use this function to implement
233 /// -save-temps. If this function returns false, any further processing for
234 /// that task is aborted.
235 ///
236 /// Module hooks must be thread safe with respect to the linker's internal
237 /// data structures. A module hook will never be called concurrently from
238 /// multiple threads with the same task ID, or the same module.
239 ///
240 /// Note that in out-of-process backend scenarios, none of the hooks will be
241 /// called for ThinLTO tasks.
242 using ModuleHookFn = std::function<bool(unsigned Task, const Module &)>;
243
244 /// This module hook is called after linking (regular LTO) or loading
245 /// (ThinLTO) the module, before modifying it.
247
248 /// This hook is called after promoting any internal functions
249 /// (ThinLTO-specific).
251
252 /// This hook is called after internalizing the module.
254
255 /// This hook is called after importing from other modules (ThinLTO-specific).
257
258 /// This module hook is called after optimization is complete.
260
261 /// This module hook is called before code generation. It is similar to the
262 /// PostOptModuleHook, but for parallel code generation it is called after
263 /// splitting the module.
265
266 /// A combined index hook is called after all per-module indexes have been
267 /// combined (ThinLTO-specific). It can be used to implement -save-temps for
268 /// the combined index.
269 ///
270 /// If this function returns false, any further processing for ThinLTO tasks
271 /// is aborted.
272 ///
273 /// It is called regardless of whether the backend is in-process, although it
274 /// is not called from individual backend processes.
275 using CombinedIndexHookFn = std::function<bool(
276 const ModuleSummaryIndex &Index,
277 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)>;
279
280 /// This hook is called after regular LTO modules with summaries (e.g., split
281 /// LTO units) have been linked into the combined module, before optimizing
282 /// the combined module or running ThinLTO.
283 using PostRegularLTOLinkHookFn = std::function<void()>;
285
286 /// This is a convenience function that configures this Config object to write
287 /// temporary files named after the given OutputFileName for each of the LTO
288 /// phases to disk. A client can use this function to implement -save-temps.
289 ///
290 /// FIXME: Temporary files derived from ThinLTO backends are currently named
291 /// after the input file name, rather than the output file name, when
292 /// UseInputModulePath is set to true.
293 ///
294 /// Specifically, it (1) sets each of the above module hooks and the combined
295 /// index hook to a function that calls the hook function (if any) that was
296 /// present in the appropriate field when the addSaveTemps function was
297 /// called, and writes the module to a bitcode file with a name prefixed by
298 /// the given output file name, and (2) creates a resolution file whose name
299 /// is prefixed by the given output file name and sets ResolutionFile to its
300 /// file handle.
301 ///
302 /// SaveTempsArgs can be specified to select which temps to save.
303 /// If SaveTempsArgs is not provided, all temps are saved.
304 LLVM_ABI Error addSaveTemps(std::string OutputFileName,
305 bool UseInputModulePath = false,
306 const DenseSet<StringRef> &SaveTempsArgs = {});
307
308 /// Called by WriteIndexesThinBackend when it needs to write a bitcode
309 /// module's summary index. The callback should return a stream to write
310 /// the index into. If not set, the backend falls back
311 /// to writing the summary index to a file.
312 std::function<std::unique_ptr<raw_pwrite_stream>(size_t Task)>
314 /// Called by WriteIndexesThinBackend when it needs to store a bitcode
315 /// module's imports list. The callback should return a vector that the
316 /// backend will populate with the imported module paths. If not set, the
317 /// backend writes the imports list to a file instead.
318 std::function<std::vector<std::string> &(size_t Task)>
320 /// Called by WriteIndexesThinBackend when it needs to store a bitcode
321 /// module's cache key. The callback should return a string that the backend
322 /// will fill with the computed cache key. If not set, the cache key is
323 /// discarded.
324 std::function<std::string &(size_t Task)> GetCacheKeyOutputString;
325};
326
330 : Fn(DiagHandlerFn) {}
331 bool handleDiagnostics(const DiagnosticInfo &DI) override {
332 (*Fn)(DI);
333 return true;
334 }
335};
336/// A derived class of LLVMContext that initializes itself according to a given
337/// Config object. The purpose of this class is to tie ownership of the
338/// diagnostic handler to the context, as opposed to the Config object (which
339/// may be ephemeral).
340// FIXME: This should not be required as diagnostic handler is not callback.
342
344 setDiscardValueNames(C.ShouldDiscardValueNames);
347 std::make_unique<LTOLLVMDiagnosticHandler>(&DiagHandler), true);
348 if (C.LibraryOptions)
349 getLibraryOptions().assign(*C.LibraryOptions);
350 }
352};
353
354}
355}
356
357#endif
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseSet and SmallDenseSet classes.
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
This is the base abstract class for diagnostic reporting in the backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
LLVM_ABI void enableDebugTypeODRUniquing()
LLVM_ABI LLVMContext()
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
LLVM_ABI void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
LLVM_ABI void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This class provides access to building LLVM's passes.
A loaded pass plugin.
Definition PassPlugin.h:97
Tunable parameters for passes in the default pipelines.
Definition PassBuilder.h:48
void assign(const LibraryOptionsContext &Other)
An abstract base class for streams implementations that also support a pwrite operation.
Interfaces for registering analysis passes, producing common pass manager configurations,...
This is an optimization pass for GlobalISel generic memory operations.
std::function< void(const DiagnosticInfo &)> DiagnosticHandlerFunction
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:309
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:283
DiagnosticHandler(void *DiagContext=nullptr)
LTO configuration.
Definition Config.h:44
DiagnosticHandlerFunction DiagHandler
Definition Config.h:204
bool HasWholeProgramVisibility
Asserts whether we can assume whole program visibility during the LTO link.
Definition Config.h:91
bool ValidateAllVtablesHaveTypeInfos
We're validating that all native vtables have corresponding type infos.
Definition Config.h:94
std::function< std::string &(size_t Task)> GetCacheKeyOutputString
Called by WriteIndexesThinBackend when it needs to store a bitcode module's cache key.
Definition Config.h:324
bool KeepSymbolNameCopies
If true, the LTO instance creates copies of the symbol names for LTO::run.
Definition Config.h:107
std::vector< std::string > PassPluginArgs
Definition Config.h:66
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Definition Config.h:242
PostRegularLTOLinkHookFn PostRegularLTOLinkHook
Definition Config.h:284
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition Config.h:189
bool AddFSDiscriminator
Add FSAFDO discriminators.
Definition Config.h:207
std::function< std::vector< std::string > &(size_t Task)> GetImportsListOutputArray
Called by WriteIndexesThinBackend when it needs to store a bitcode module's imports list.
Definition Config.h:319
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition Config.h:183
const cl::LibraryOptionsContext * LibraryOptions
Definition Config.h:51
LLVM_ABI Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false, const DenseSet< StringRef > &SaveTempsArgs={})
This is a convenience function that configures this Config object to write temporary files named afte...
std::string StatsFile
Statistics output file path.
Definition Config.h:192
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module,...
Definition Config.h:246
CombinedIndexHookFn CombinedIndexHook
Definition Config.h:278
std::optional< CodeModel::Model > CodeModel
Definition Config.h:69
std::string AAPipeline
Definition Config.h:128
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition Config.h:81
bool DisableVerify
Definition Config.h:74
std::vector< std::string > MAttrs
Definition Config.h:56
std::vector< std::string > MllvmArgs
Definition Config.h:57
std::vector< std::string > ThinLTOModulesToCompile
Specific thinLTO modules to compile.
Definition Config.h:195
std::function< void(PassBuilder &)> PassBuilderCallback
Definition Config.h:67
CodeGenOptLevel CGOptLevel
Definition Config.h:70
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition Config.h:216
std::vector< llvm::PassPlugin * > LoadedPassPlugins
Definition Config.h:60
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...
Definition Config.h:213
bool Dtlto
This flag is used as one of parameters to calculate cache entries and to ensure that in-process cache...
Definition Config.h:112
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple.
Definition Config.h:136
bool AlwaysEmitRegularLTOObj
Always emit a Regular LTO object even when it is empty because no Regular LTO modules were linked.
Definition Config.h:102
std::string CPU
Definition Config.h:54
std::string DwoDir
The directory to store .dwo files.
Definition Config.h:148
std::string RemarksFilename
Optimization remarks file path.
Definition Config.h:162
VisScheme VisibilityScheme
Allows non-imported definitions to get the potentially more constraining visibility from the prevaili...
Definition Config.h:118
std::function< void()> PostRegularLTOLinkHookFn
This hook is called after regular LTO modules with summaries (e.g., split LTO units) have been linked...
Definition Config.h:283
std::vector< std::string > PassPluginFilenames
Definition Config.h:64
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition Config.h:250
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition Config.h:132
std::string ProfileRemapping
Name remapping file for profile data.
Definition Config.h:145
bool AllVtablesHaveTypeInfos
If all native vtables have corresponding type infos, allow usage of RTTI to block devirtualization on...
Definition Config.h:97
TargetOptions Options
Definition Config.h:55
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
Definition Config.h:154
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition Config.h:159
bool TimeTraceEnabled
Time trace enabled.
Definition Config.h:198
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition Config.h:259
std::function< std::unique_ptr< raw_pwrite_stream >(size_t Task)> GetSummaryIndexOutputStream
Called by WriteIndexesThinBackend when it needs to write a bitcode module's summary index.
Definition Config.h:313
std::string RemarksPasses
Optimization remarks pass filter.
Definition Config.h:165
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition Config.h:123
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition Config.h:84
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition Config.h:253
unsigned TimeTraceGranularity
Time trace granularity.
Definition Config.h:201
unsigned OptLevel
Definition Config.h:72
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition Config.h:256
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition Config.h:168
std::function< bool( const ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)> CombinedIndexHookFn
A combined index hook is called after all per-module indexes have been combined (ThinLTO-specific).
Definition Config.h:275
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition Config.h:139
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition Config.h:264
std::optional< Reloc::Model > RelocModel
Definition Config.h:68
bool ShouldDiscardValueNames
Definition Config.h:203
bool PGOWarnMismatch
Turn on/off the warning about a hash mismatch in the PGO profile data.
Definition Config.h:87
CodeGenFileType CGFileType
Definition Config.h:71
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:78
std::string SampleProfile
Sample PGO profile path.
Definition Config.h:142
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition Config.h:186
DiagnosticHandlerFunction DiagHandler
Definition Config.h:351
LTOLLVMContext(const Config &C)
Definition Config.h:343
LTOLLVMDiagnosticHandler(DiagnosticHandlerFunction *DiagHandlerFn)
Definition Config.h:329
DiagnosticHandlerFunction * Fn
Definition Config.h:328
bool handleDiagnostics(const DiagnosticInfo &DI) override
Override handleDiagnostics to provide custom implementation.
Definition Config.h:331