LLVM 24.0.0git
ThinLTOCodeGenerator.h
Go to the documentation of this file.
1//===-ThinLTOCodeGenerator.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 ThinLTOCodeGenerator class, similar to the
10// LTOCodeGenerator but for the ThinLTO scheme. It provides an interface for
11// linker plugin.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_LTO_LEGACY_THINLTOCODEGENERATOR_H
16#define LLVM_LTO_LEGACY_THINLTOCODEGENERATOR_H
17
18#include "llvm-c/lto.h"
19#include "llvm/ADT/StringSet.h"
21#include "llvm/LTO/LTO.h"
28
29#include <string>
30
31namespace llvm {
32class StringRef;
33class TargetMachine;
34
35/// ThinLTOCodeGeneratorImpl - Namespace used for ThinLTOCodeGenerator
36/// implementation details. It should be considered private to the
37/// implementation.
41
42/// Helper to gather options relevant to the target machine creation
45 std::string MCpu;
46 std::string MAttr;
48 std::optional<Reloc::Model> RelocModel;
50
51 LLVM_ABI std::unique_ptr<TargetMachine> create() const;
52};
53
54/// This class define an interface similar to the LTOCodeGenerator, but adapted
55/// for ThinLTO processing.
56/// The ThinLTOCodeGenerator is not intended to be reuse for multiple
57/// compilation: the model is that the client adds modules to the generator and
58/// ask to perform the ThinLTO optimizations / codegen, and finally destroys the
59/// codegenerator.
61public:
62 /// The target machines and the LLVMContexts that run() creates read
63 /// \p LibraryOptions, which must outlive the generator.
64 explicit ThinLTOCodeGenerator(const cl::LibraryOptionsContext &LibraryOptions)
65 : LibraryOptions(LibraryOptions) {
66 TMBuilder.Options.MCOptions.LibraryOptions = &LibraryOptions;
67 }
68
69 /// Add given module to the code generator.
70 LLVM_ABI void addModule(StringRef Identifier, StringRef Data);
71
72 /**
73 * Adds to a list of all global symbols that must exist in the final generated
74 * code. If a symbol is not listed there, it will be optimized away if it is
75 * inlined into every usage.
76 */
78
79 /**
80 * Adds to a list of all global symbols that are cross-referenced between
81 * ThinLTO files. If the ThinLTO CodeGenerator can ensure that every
82 * references from a ThinLTO module to this symbol is optimized away, then
83 * the symbol can be discarded.
84 */
86
87 /**
88 * Process all the modules that were added to the code generator in parallel.
89 *
90 * Client can access the resulting object files using getProducedBinaries(),
91 * unless setGeneratedObjectsDirectory() has been called, in which case
92 * results are available through getProducedBinaryFiles().
93 */
94 LLVM_ABI void run();
95
96 /**
97 * Return the "in memory" binaries produced by the code generator. This is
98 * filled after run() unless setGeneratedObjectsDirectory() has been
99 * called, in which case results are available through
100 * getProducedBinaryFiles().
101 */
102 std::vector<std::unique_ptr<MemoryBuffer>> &getProducedBinaries() {
103 return ProducedBinaries;
104 }
105
106 /**
107 * Return the "on-disk" binaries produced by the code generator. This is
108 * filled after run() when setGeneratedObjectsDirectory() has been
109 * called, in which case results are available through getProducedBinaries().
110 */
111 std::vector<std::string> &getProducedBinaryFiles() {
112 return ProducedBinaryFiles;
113 }
114
115 /**
116 * \defgroup Options setters
117 * @{
118 */
119
120 /**
121 * \defgroup Cache controlling options
122 *
123 * These entry points control the ThinLTO cache. The cache is intended to
124 * support incremental build, and thus needs to be persistent accross build.
125 * The client enabled the cache by supplying a path to an existing directory.
126 * The code generator will use this to store objects files that may be reused
127 * during a subsequent build.
128 * To avoid filling the disk space, a few knobs are provided:
129 * - The pruning interval limit the frequency at which the garbage collector
130 * will try to scan the cache directory to prune it from expired entries.
131 * Setting to -1 disable the pruning (default). Setting to 0 will force
132 * pruning to occur.
133 * - The pruning expiration time indicates to the garbage collector how old
134 * an entry needs to be to be removed.
135 * - Finally, the garbage collector can be instructed to prune the cache till
136 * the occupied space goes below a threshold.
137 * @{
138 */
139
141 std::string Path; // Path to the cache, empty to disable.
143 };
144
145 /// Provide a path to a directory where to store the cached files for
146 /// incremental build.
147 void setCacheDir(std::string Path) { CacheOptions.Path = std::move(Path); }
148
149 /// Cache policy: interval (seconds) between two prunes of the cache. Set to a
150 /// negative value to disable pruning. A value of 0 will force pruning to
151 /// occur.
153 if(Interval < 0)
154 CacheOptions.Policy.Interval.reset();
155 else
156 CacheOptions.Policy.Interval = std::chrono::seconds(Interval);
157 }
158
159 /// Cache policy: expiration (in seconds) for an entry.
160 /// A value of 0 will be ignored.
161 void setCacheEntryExpiration(unsigned Expiration) {
162 if (Expiration)
163 CacheOptions.Policy.Expiration = std::chrono::seconds(Expiration);
164 }
165
166 /**
167 * Sets the maximum cache size that can be persistent across build, in terms
168 * of percentage of the available space on the disk. Set to 100 to indicate
169 * no limit, 50 to indicate that the cache size will not be left over
170 * half the available space. A value over 100 will be reduced to 100, and a
171 * value of 0 will be ignored.
172 *
173 *
174 * The formula looks like:
175 * AvailableSpace = FreeSpace + ExistingCacheSize
176 * NewCacheSize = AvailableSpace * P/100
177 *
178 */
179 void setMaxCacheSizeRelativeToAvailableSpace(unsigned Percentage) {
180 if (Percentage)
181 CacheOptions.Policy.MaxSizePercentageOfAvailableSpace = Percentage;
182 }
183
184 /// Cache policy: the maximum size for the cache directory in bytes. A value
185 /// over the amount of available space on the disk will be reduced to the
186 /// amount of available space. A value of 0 will be ignored.
187 void setCacheMaxSizeBytes(uint64_t MaxSizeBytes) {
188 if (MaxSizeBytes)
189 CacheOptions.Policy.MaxSizeBytes = MaxSizeBytes;
190 }
191
192 /// Cache policy: the maximum number of files in the cache directory. A value
193 /// of 0 will be ignored.
194 void setCacheMaxSizeFiles(unsigned MaxSizeFiles) {
195 if (MaxSizeFiles)
196 CacheOptions.Policy.MaxSizeFiles = MaxSizeFiles;
197 }
198
199 /**@}*/
200
201 /// Set the path to a directory where to save temporaries at various stages of
202 /// the processing.
203 void setSaveTempsDir(std::string Path) { SaveTempsDir = std::move(Path); }
204
205 /// Set the path to a directory where to save generated object files. This
206 /// path can be used by a linker to request on-disk files instead of in-memory
207 /// buffers. When set, results are available through getProducedBinaryFiles()
208 /// instead of getProducedBinaries().
209 void setGeneratedObjectsDirectory(std::string Path) {
210 SavedObjectsDirectoryPath = std::move(Path);
211 }
212
213 /// CPU to use to initialize the TargetMachine
214 void setCpu(std::string Cpu) { TMBuilder.MCpu = std::move(Cpu); }
215
216 /// Subtarget attributes
217 void setAttr(std::string MAttr) { TMBuilder.MAttr = std::move(MAttr); }
218
219 /// TargetMachine options
221 TMBuilder.Options = std::move(Options);
222 TMBuilder.Options.MCOptions.LibraryOptions = &LibraryOptions;
223 }
224
225 /// Enable the Freestanding mode: indicate that the optimizer should not
226 /// assume builtins are present on the target.
227 void setFreestanding(bool Enabled) { Freestanding = Enabled; }
228
229 /// CodeModel
230 void setCodePICModel(std::optional<Reloc::Model> Model) {
231 TMBuilder.RelocModel = Model;
232 }
233
234 /// CodeGen optimization level
236 TMBuilder.CGOptLevel = CGOptLevel;
237 }
238
239 /// IR optimization level: from 0 to 3.
240 void setOptLevel(unsigned NewOptLevel) {
241 OptLevel = (NewOptLevel > 3) ? 3 : NewOptLevel;
242 }
243
244 /// Enable or disable debug output for the new pass manager.
245 void setDebugPassManager(unsigned Enabled) { DebugPassManager = Enabled; }
246
247 /// Set the -mllvm arguments to include in the cache key.
249 MllvmArgs.assign(Args.begin(), Args.end());
250 }
251
252 /// Disable CodeGen, only run the stages till codegen and stop. The output
253 /// will be bitcode.
254 void disableCodeGen(bool Disable) { DisableCodeGen = Disable; }
255
256 /// Perform CodeGen only: disable all other stages.
257 void setCodeGenOnly(bool CGOnly) { CodeGenOnly = CGOnly; }
258
259 /**@}*/
260
261 /**
262 * \defgroup Set of APIs to run individual stages in isolation.
263 * @{
264 */
265
266 /**
267 * Produce the combined summary index from all the bitcode files:
268 * "thin-link".
269 */
270 LLVM_ABI std::unique_ptr<ModuleSummaryIndex> linkCombinedIndex();
271
272 /**
273 * Perform promotion and renaming of exported internal functions,
274 * and additionally resolve weak and linkonce symbols.
275 * Index is updated to reflect linkage changes from weak resolution.
276 */
278 const lto::InputFile &File);
279
280 /**
281 * Compute and emit the imported files for module at \p ModulePath.
282 */
283 LLVM_ABI void emitImports(Module &Module, StringRef OutputName,
284 ModuleSummaryIndex &Index,
285 const lto::InputFile &File);
286
287 /**
288 * Perform cross-module importing for the module identified by
289 * ModuleIdentifier.
290 */
292 const lto::InputFile &File);
293
294 /**
295 * Compute the list of summaries and the subset of declaration summaries
296 * needed for importing into module.
297 */
300 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
301 GVSummaryPtrSet &DecSummaries, const lto::InputFile &File);
302
303 /**
304 * Perform internalization. Index is updated to reflect linkage changes.
305 */
307 const lto::InputFile &File);
308
309 /**
310 * Perform post-importing ThinLTO optimizations.
311 */
313
314 /**
315 * Write temporary object file to SavedObjectDirectoryPath, write symlink
316 * to Cache directory if needed. Returns the path to the generated file in
317 * SavedObjectsDirectoryPath.
318 */
319 LLVM_ABI std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
321 /**@}*/
322
323private:
324 const cl::LibraryOptionsContext &LibraryOptions;
325
326 /// Helper factory to build a TargetMachine
328
329 /// Vector holding the in-memory buffer containing the produced binaries, when
330 /// SavedObjectsDirectoryPath isn't set.
331 std::vector<std::unique_ptr<MemoryBuffer>> ProducedBinaries;
332
333 /// Path to generated files in the supplied SavedObjectsDirectoryPath if any.
334 std::vector<std::string> ProducedBinaryFiles;
335
336 /// Vector holding the input buffers containing the bitcode modules to
337 /// process.
338 std::vector<std::unique_ptr<lto::InputFile>> Modules;
339
340 /// Set of symbols that need to be preserved outside of the set of bitcode
341 /// files.
342 StringSet<> PreservedSymbols;
343
344 /// Set of symbols that are cross-referenced between bitcode files.
345 StringSet<> CrossReferencedSymbols;
346
347 /// Control the caching behavior.
348 CachingOptions CacheOptions;
349
350 /// Path to a directory to save the temporary bitcode files.
351 std::string SaveTempsDir;
352
353 /// Path to a directory to save the generated object files.
354 std::string SavedObjectsDirectoryPath;
355
356 /// Flag to enable/disable CodeGen. When set to true, the process stops after
357 /// optimizations and a bitcode is produced.
358 bool DisableCodeGen = false;
359
360 /// Flag to indicate that only the CodeGen will be performed, no cross-module
361 /// importing or optimization.
362 bool CodeGenOnly = false;
363
364 /// Flag to indicate that the optimizer should not assume builtins are present
365 /// on the target.
366 bool Freestanding = false;
367
368 /// IR Optimization Level [0-3].
369 unsigned OptLevel = 3;
370
371 /// Flag to indicate whether debug output should be enabled for the new pass
372 /// manager.
373 bool DebugPassManager = false;
374
375 /// -mllvm arguments included in the cache key.
376 std::vector<std::string> MllvmArgs;
377};
378}
379#endif
uint64_t uint64_t
#define LLVM_ABI
Definition Compiler.h:211
static LVOptions Options
Definition LVOptions.cpp:25
std::pair< uint64_t, uint64_t > Interval
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
StringSet - A set-like wrapper for the StringMap.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This interface provides simple read-only access to a block of memory, and provides simple methods for...
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
Primary interface to the complete machine description for the target machine.
LLVM_ABI void preserveSymbol(StringRef Name)
Adds to a list of all global symbols that must exist in the final generated code.
std::vector< std::unique_ptr< MemoryBuffer > > & getProducedBinaries()
Return the "in memory" binaries produced by the code generator.
ThinLTOCodeGenerator(const cl::LibraryOptionsContext &LibraryOptions)
The target machines and the LLVMContexts that run() creates read LibraryOptions, which must outlive t...
LLVM_ABI void run()
Process all the modules that were added to the code generator in parallel.
LLVM_ABI void crossReferenceSymbol(StringRef Name)
Adds to a list of all global symbols that are cross-referenced between ThinLTO files.
LLVM_ABI void addModule(StringRef Identifier, StringRef Data)
Add given module to the code generator.
std::vector< std::string > & getProducedBinaryFiles()
Return the "on-disk" binaries produced by the code generator.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
An input file.
Definition LTO.h:115
void setCacheDir(std::string Path)
Provide a path to a directory where to store the cached files for incremental build.
void setCachePruningInterval(int Interval)
Cache policy: interval (seconds) between two prunes of the cache.
void setCacheEntryExpiration(unsigned Expiration)
Cache policy: expiration (in seconds) for an entry.
void setMaxCacheSizeRelativeToAvailableSpace(unsigned Percentage)
Sets the maximum cache size that can be persistent across build, in terms of percentage of the availa...
void setCacheMaxSizeBytes(uint64_t MaxSizeBytes)
Cache policy: the maximum size for the cache directory in bytes.
void setCacheMaxSizeFiles(unsigned MaxSizeFiles)
Cache policy: the maximum number of files in the cache directory.
void setCpu(std::string Cpu)
CPU to use to initialize the TargetMachine.
void disableCodeGen(bool Disable)
Disable CodeGen, only run the stages till codegen and stop.
void setGeneratedObjectsDirectory(std::string Path)
Set the path to a directory where to save generated object files.
void setTargetOptions(TargetOptions Options)
TargetMachine options.
void setOptLevel(unsigned NewOptLevel)
IR optimization level: from 0 to 3.
void setMllvmArgs(ArrayRef< std::string > Args)
Set the -mllvm arguments to include in the cache key.
void setAttr(std::string MAttr)
Subtarget attributes.
void setFreestanding(bool Enabled)
Enable the Freestanding mode: indicate that the optimizer should not assume builtins are present on t...
void setSaveTempsDir(std::string Path)
Set the path to a directory where to save temporaries at various stages of the processing.
void setCodeGenOnly(bool CGOnly)
Perform CodeGen only: disable all other stages.
void setDebugPassManager(unsigned Enabled)
Enable or disable debug output for the new pass manager.
void setCodePICModel(std::optional< Reloc::Model > Model)
CodeModel.
void setCodeGenOptLevel(CodeGenOptLevel CGOptLevel)
CodeGen optimization level.
LLVM_ABI void optimize(Module &Module)
Perform post-importing ThinLTO optimizations.
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > linkCombinedIndex()
Produce the combined summary index from all the bitcode files: "thin-link".
LLVM_ABI void crossModuleImport(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform cross-module importing for the module identified by ModuleIdentifier.
LLVM_ABI void emitImports(Module &Module, StringRef OutputName, ModuleSummaryIndex &Index, const lto::InputFile &File)
Compute and emit the imported files for module at ModulePath.
LLVM_ABI void internalize(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform internalization.
LLVM_ABI void gatherImportedSummariesForModule(Module &Module, ModuleSummaryIndex &Index, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries, const lto::InputFile &File)
Compute the list of summaries and the subset of declaration summaries needed for importing into modul...
LLVM_ABI void promote(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
LLVM_ABI std::string writeGeneratedObject(int count, StringRef CacheEntryPath, const MemoryBuffer &OutputBuffer)
Write temporary object file to SavedObjectDirectoryPath, write symlink to Cache directory if needed.
ThinLTOCodeGeneratorImpl - Namespace used for ThinLTOCodeGenerator implementation details.
This is an optimization pass for GlobalISel generic memory operations.
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
@ Disable
Disable colors.
Definition WithColor.h:49
Policy for the pruneCache() function.
Helper to gather options relevant to the target machine creation.
LLVM_ABI std::unique_ptr< TargetMachine > create() const