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