LLVM 24.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// FIXME: populateLTOPassManager no longer exists.
28//
29// The "LTOCodeGenerator" is the driver for the IPO and Post-IPO stages.
30// The "CodeGenerator" here is bit confusing. Don't confuse the "CodeGenerator"
31// with the machine specific code generator.
32//
33//===----------------------------------------------------------------------===//
34
35#ifndef LLVM_LTO_LEGACY_LTOCODEGENERATOR_H
36#define LLVM_LTO_LEGACY_LTOCODEGENERATOR_H
37
38#include "llvm-c/lto.h"
39#include "llvm/ADT/ArrayRef.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"
48#include "llvm/Support/Error.h"
52#include <string>
53#include <vector>
54
55namespace llvm {
56template <typename T> class ArrayRef;
57class LLVMContext;
58class DiagnosticInfo;
59class Linker;
60class MemoryBuffer;
61class TargetMachine;
62
63/// Enable global value internalization in LTO.
65
66//===----------------------------------------------------------------------===//
67/// C++ class which implements the opaque lto_code_gen_t type.
68///
70 LLVM_ABI static const char *getVersionString();
71
74
75 /// Merge given module. Return true on success.
76 ///
77 /// Resets \a HasVerifiedInput.
78 LLVM_ABI bool addModule(struct LTOModule *);
79
80 /// Set the destination module.
81 ///
82 /// Resets \a HasVerifiedInput.
83 LLVM_ABI void setModule(std::unique_ptr<LTOModule> M);
84
88 void setCodePICModel(std::optional<Reloc::Model> Model) {
89 Config.RelocModel = Model;
90 }
91
92 /// Set the file type to be emitted (assembly or object code).
93 /// The default is CodeGenFileType::ObjectFile.
94 void setFileType(CodeGenFileType FT) { Config.CGFileType = FT; }
95
96 void setCpu(StringRef MCpu) { Config.CPU = std::string(MCpu); }
97 void setAttrs(std::vector<std::string> MAttrs) {
98 Config.MAttrs = std::move(MAttrs);
99 }
100 LLVM_ABI void setOptLevel(unsigned OptLevel);
101
102 void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
103 void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }
104 void setSaveIRBeforeOptPath(std::string Value) {
105 SaveIRBeforeOptPath = std::move(Value);
106 }
107
108 /// Restore linkage of globals
109 ///
110 /// When set, the linkage of globals will be restored prior to code
111 /// generation. That is, a global symbol that had external linkage prior to
112 /// LTO will be emitted with external linkage again; and a local will remain
113 /// local. Note that this option only affects the end result - globals may
114 /// still be internalized in the process of LTO and may be modified and/or
115 /// deleted where legal.
116 ///
117 /// The default behavior will internalize globals (unless on the preserve
118 /// list) and, if parallel code generation is enabled, will externalize
119 /// all locals.
121 ShouldRestoreGlobalsLinkage = Value;
122 }
123
124 void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols.insert(Sym); }
125
126 /// Pass options to the driver and optimization passes.
127 ///
128 /// These options are not necessarily for debugging purpose (the function
129 /// name is misleading). This function should be called before
130 /// LTOCodeGenerator::compilexxx(), and
131 /// LTOCodeGenerator::writeMergedModules().
133
134 /// Parse the options set in setCodeGenDebugOptions.
135 ///
136 /// Like \a setCodeGenDebugOptions(), this must be called before
137 /// LTOCodeGenerator::compilexxx() and
138 /// LTOCodeGenerator::writeMergedModules().
140
141 /// Write the merged module to the file specified by the given path. Return
142 /// true on success.
143 ///
144 /// Calls \a verifyMergedModuleOnce().
146
147 /// Compile the merged module into a *single* output file; the path to output
148 /// file is returned to the caller via argument "name". Return true on
149 /// success.
150 ///
151 /// \note It is up to the linker to remove the intermediate output file. Do
152 /// not try to remove the object file in LTOCodeGenerator's destructor as we
153 /// don't who (LTOCodeGenerator or the output file) will last longer.
154 LLVM_ABI bool compile_to_file(const char **Name);
155
156 /// As with compile_to_file(), this function compiles the merged module into
157 /// single output file. Instead of returning the output file path to the
158 /// caller (linker), it brings the output to a buffer, and returns the buffer
159 /// to the caller. This function should delete the intermediate file once
160 /// its content is brought to memory. Return NULL if the compilation was not
161 /// successful.
162 LLVM_ABI std::unique_ptr<MemoryBuffer> compile();
163
164 /// Optimizes the merged module. Returns true on success.
165 ///
166 /// Calls \a verifyMergedModuleOnce().
167 LLVM_ABI bool optimize();
168
169 /// Compiles the merged optimized module into a single output file. It brings
170 /// the output to a buffer, and returns the buffer to the caller. Return NULL
171 /// if the compilation was not successful.
172 LLVM_ABI std::unique_ptr<MemoryBuffer> compileOptimized();
173
174 /// Compile the merged optimized module \p ParallelismLevel output files each
175 /// representing a linkable partition of the module. If out contains more
176 /// than one element, code generation is done in parallel with \p
177 /// ParallelismLevel threads. Output files will be written to the streams
178 /// created using the \p AddStream callback. Returns true on success.
179 ///
180 /// Calls \a verifyMergedModuleOnce().
182 unsigned ParallelismLevel);
183
184 /// Enable the Freestanding mode: indicate that the optimizer should not
185 /// assume builtins are present on the target.
186 void setFreestanding(bool Enabled) { Config.Freestanding = Enabled; }
187
188 void setDisableVerify(bool Value) { Config.DisableVerify = Value; }
189
190 void setDebugPassManager(bool Enabled) { Config.DebugPassManager = Enabled; }
191
193
194 LLVMContext &getContext() { return Context; }
195
196 void resetMergedModule() { MergedModule.reset(); }
198
199private:
200 /// Verify the merged module on first call.
201 ///
202 /// Sets \a HasVerifiedInput on first call and doesn't run again on the same
203 /// input.
204 void verifyMergedModuleOnce();
205
206 bool compileOptimizedToFile(const char **Name);
207 void restoreLinkageForExternals();
208 void applyScopeRestrictions();
209 void preserveDiscardableGVs(
210 Module &TheModule,
212
213 bool determineTarget();
214 std::unique_ptr<TargetMachine> createTargetMachine();
215
216 bool useAIXSystemAssembler();
217 bool runAIXSystemAssembler(SmallString<128> &AssemblyFile);
218
219 void emitError(const std::string &ErrMsg);
220 void emitWarning(const std::string &ErrMsg);
221
222 void finishOptimizationRemarks();
223
225 std::unique_ptr<Module> MergedModule;
226 std::unique_ptr<Linker> TheLinker;
227 std::unique_ptr<TargetMachine> TargetMach;
228 bool EmitDwarfDebugInfo = false;
229 bool ScopeRestrictionsDone = false;
230 bool HasVerifiedInput = false;
231 StringSet<> MustPreserveSymbols;
232 StringSet<> AsmUndefinedRefs;
234 std::vector<std::string> CodegenOptions;
235 std::string FeatureStr;
236 std::string NativeObjectPath;
237 const Target *MArch = nullptr;
239 void *DiagContext = nullptr;
240 bool ShouldInternalize = EnableLTOInternalization;
241 bool ShouldEmbedUselists = false;
242 bool ShouldRestoreGlobalsLinkage = false;
243 LLVMRemarkFileHandle DiagnosticOutputFile;
244 std::unique_ptr<ToolOutputFile> StatsFile = nullptr;
245 std::string SaveIRBeforeOptPath;
246
247 lto::Config Config;
248};
249} // namespace llvm
250#endif
This file defines the StringMap class.
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
#define LLVM_ABI
Definition Compiler.h:211
Module.h This file contains the declarations for the Module class.
static std::unique_ptr< TargetMachine > createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M)
static LVOptions Options
Definition LVOptions.cpp:25
StringSet - A set-like wrapper for the StringMap.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This is the base abstract class for diagnostic reporting in the backend.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
RAII handle that manages the lifetime of the ToolOutputFile used to output remarks.
This class provides the core functionality of linking in LLVM.
Definition Linker.h:23
This interface provides simple read-only access to a block of memory, and provides simple methods for...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
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:27
Primary interface to the complete machine description for the target machine.
Target - Wrapper for Target specific information.
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
lto_debug_model
Definition lto.h:80
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition lto.h:354
This is an optimization pass for GlobalISel generic memory operations.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:309
LLVM_ABI cl::opt< bool > EnableLTOInternalization
Enable global value internalization in LTO.
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:79
LLVM_ABI bool optimize()
Optimizes the merged module.
LLVM_ABI std::unique_ptr< MemoryBuffer > compile()
As with compile_to_file(), this function compiles the merged module into single output file.
LLVM_ABI void setModule(std::unique_ptr< LTOModule > M)
Set the destination module.
LLVM_ABI 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...
void setCpu(StringRef MCpu)
void addMustPreserveSymbol(StringRef Sym)
void setShouldInternalize(bool Value)
void setAttrs(std::vector< std::string > MAttrs)
LLVM_ABI void parseCodeGenDebugOptions()
Parse the options set in setCodeGenDebugOptions.
LLVM_ABI void setOptLevel(unsigned OptLevel)
LLVM_ABI void setAsmUndefinedRefs(struct LTOModule *)
LLVM_ABI void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
void setFileType(CodeGenFileType FT)
Set the file type to be emitted (assembly or object code).
LLVM_ABI void setTargetOptions(const TargetOptions &Options)
LLVM_ABI void setCodeGenDebugOptions(ArrayRef< StringRef > Opts)
Pass options to the driver and optimization passes.
LLVM_ABI LTOCodeGenerator(LLVMContext &Context)
void setCodePICModel(std::optional< Reloc::Model > Model)
LLVM_ABI std::unique_ptr< MemoryBuffer > compileOptimized()
Compiles the merged optimized module into a single output file.
void setDebugPassManager(bool Enabled)
LLVM_ABI bool addModule(struct LTOModule *)
Merge given module.
LLVM_ABI void setDebugInfo(lto_debug_model)
void setSaveIRBeforeOptPath(std::string Value)
void setDisableVerify(bool Value)
void setShouldEmbedUselists(bool Value)
LLVM_ABI ~LTOCodeGenerator()
LLVM_ABI bool writeMergedModules(StringRef Path)
Write the merged module to the file specified by the given path.
LLVM_ABI void DiagnosticHandler(const DiagnosticInfo &DI)
static LLVM_ABI const char * getVersionString()
void setShouldRestoreGlobalsLinkage(bool Value)
Restore linkage of globals.
void setFreestanding(bool Enabled)
Enable the Freestanding mode: indicate that the optimizer should not assume builtins are present on t...
C++ class which implements the opaque lto_module_t type.
Definition LTOModule.h:39
LTO configuration.
Definition Config.h:44