LLVM  9.0.0svn
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_LTOCODEGENERATOR_H
35 #define LLVM_LTO_LTOCODEGENERATOR_H
36 
37 #include "llvm-c/lto.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/StringMap.h"
40 #include "llvm/ADT/StringSet.h"
41 #include "llvm/IR/GlobalValue.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/Support/Error.h"
47 #include <string>
48 #include <vector>
49 
50 /// Enable global value internalization in LTO.
52 
53 namespace llvm {
54 template <typename T> class ArrayRef;
55  class LLVMContext;
56  class DiagnosticInfo;
57  class Linker;
58  class Mangler;
59  class MemoryBuffer;
60  class TargetLibraryInfo;
61  class TargetMachine;
62  class raw_ostream;
63  class raw_pwrite_stream;
64 
65 //===----------------------------------------------------------------------===//
66 /// C++ class which implements the opaque lto_code_gen_t type.
67 ///
69  static const char *getVersionString();
70 
71  LTOCodeGenerator(LLVMContext &Context);
73 
74  /// Merge given module. Return true on success.
75  ///
76  /// Resets \a HasVerifiedInput.
77  bool addModule(struct LTOModule *);
78 
79  /// Set the destination module.
80  ///
81  /// Resets \a HasVerifiedInput.
82  void setModule(std::unique_ptr<LTOModule> M);
83 
84  void setAsmUndefinedRefs(struct LTOModule *);
85  void setTargetOptions(const TargetOptions &Options);
88 
89  /// Set the file type to be emitted (assembly or object code).
90  /// The default is TargetMachine::CGFT_ObjectFile.
91  void setFileType(TargetMachine::CodeGenFileType FT) { FileType = FT; }
92 
93  void setCpu(StringRef MCpu) { this->MCpu = MCpu; }
94  void setAttr(StringRef MAttr) { this->MAttr = MAttr; }
95  void setOptLevel(unsigned OptLevel);
96 
97  void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
98  void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }
99 
100  /// Restore linkage of globals
101  ///
102  /// When set, the linkage of globals will be restored prior to code
103  /// generation. That is, a global symbol that had external linkage prior to
104  /// LTO will be emitted with external linkage again; and a local will remain
105  /// local. Note that this option only affects the end result - globals may
106  /// still be internalized in the process of LTO and may be modified and/or
107  /// deleted where legal.
108  ///
109  /// The default behavior will internalize globals (unless on the preserve
110  /// list) and, if parallel code generation is enabled, will externalize
111  /// all locals.
113  ShouldRestoreGlobalsLinkage = Value;
114  }
115 
116  void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols[Sym] = 1; }
117 
118  /// Pass options to the driver and optimization passes.
119  ///
120  /// These options are not necessarily for debugging purpose (the function
121  /// name is misleading). This function should be called before
122  /// LTOCodeGenerator::compilexxx(), and
123  /// LTOCodeGenerator::writeMergedModules().
125 
126  /// Parse the options set in setCodeGenDebugOptions.
127  ///
128  /// Like \a setCodeGenDebugOptions(), this must be called before
129  /// LTOCodeGenerator::compilexxx() and
130  /// LTOCodeGenerator::writeMergedModules().
132 
133  /// Write the merged module to the file specified by the given path. Return
134  /// true on success.
135  ///
136  /// Calls \a verifyMergedModuleOnce().
137  bool writeMergedModules(StringRef Path);
138 
139  /// Compile the merged module into a *single* output file; the path to output
140  /// file is returned to the caller via argument "name". Return true on
141  /// success.
142  ///
143  /// \note It is up to the linker to remove the intermediate output file. Do
144  /// not try to remove the object file in LTOCodeGenerator's destructor as we
145  /// don't who (LTOCodeGenerator or the output file) will last longer.
146  bool compile_to_file(const char **Name, bool DisableVerify,
147  bool DisableInline, bool DisableGVNLoadPRE,
148  bool DisableVectorization);
149 
150  /// As with compile_to_file(), this function compiles the merged module into
151  /// single output file. Instead of returning the output file path to the
152  /// caller (linker), it brings the output to a buffer, and returns the buffer
153  /// to the caller. This function should delete the intermediate file once
154  /// its content is brought to memory. Return NULL if the compilation was not
155  /// successful.
156  std::unique_ptr<MemoryBuffer> compile(bool DisableVerify, bool DisableInline,
157  bool DisableGVNLoadPRE,
158  bool DisableVectorization);
159 
160  /// Optimizes the merged module. Returns true on success.
161  ///
162  /// Calls \a verifyMergedModuleOnce().
163  bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE,
164  bool DisableVectorization);
165 
166  /// Compiles the merged optimized module into a single output file. It brings
167  /// the output to a buffer, and returns the buffer to the caller. Return NULL
168  /// if the compilation was not successful.
169  std::unique_ptr<MemoryBuffer> compileOptimized();
170 
171  /// Compile the merged optimized module into out.size() output files each
172  /// representing a linkable partition of the module. If out contains more
173  /// than one element, code generation is done in parallel with out.size()
174  /// threads. Output files will be written to members of out. Returns true on
175  /// success.
176  ///
177  /// Calls \a verifyMergedModuleOnce().
179 
180  /// Enable the Freestanding mode: indicate that the optimizer should not
181  /// assume builtins are present on the target.
182  void setFreestanding(bool Enabled) { Freestanding = Enabled; }
183 
185 
186  LLVMContext &getContext() { return Context; }
187 
188  void resetMergedModule() { MergedModule.reset(); }
189  void DiagnosticHandler(const DiagnosticInfo &DI);
190 
191 private:
192  void initializeLTOPasses();
193 
194  /// Verify the merged module on first call.
195  ///
196  /// Sets \a HasVerifiedInput on first call and doesn't run again on the same
197  /// input.
198  void verifyMergedModuleOnce();
199 
200  bool compileOptimizedToFile(const char **Name);
201  void restoreLinkageForExternals();
202  void applyScopeRestrictions();
203  void preserveDiscardableGVs(
204  Module &TheModule,
206 
207  bool determineTarget();
208  std::unique_ptr<TargetMachine> createTargetMachine();
209 
210  void emitError(const std::string &ErrMsg);
211  void emitWarning(const std::string &ErrMsg);
212 
213  void finishOptimizationRemarks();
214 
215  LLVMContext &Context;
216  std::unique_ptr<Module> MergedModule;
217  std::unique_ptr<Linker> TheLinker;
218  std::unique_ptr<TargetMachine> TargetMach;
219  bool EmitDwarfDebugInfo = false;
220  bool ScopeRestrictionsDone = false;
221  bool HasVerifiedInput = false;
222  Optional<Reloc::Model> RelocModel;
223  StringSet<> MustPreserveSymbols;
224  StringSet<> AsmUndefinedRefs;
225  StringMap<GlobalValue::LinkageTypes> ExternalSymbols;
226  std::vector<std::string> CodegenOptions;
227  std::string FeatureStr;
228  std::string MCpu;
229  std::string MAttr;
230  std::string NativeObjectPath;
231  TargetOptions Options;
233  const Target *MArch = nullptr;
234  std::string TripleStr;
235  unsigned OptLevel = 2;
236  lto_diagnostic_handler_t DiagHandler = nullptr;
237  void *DiagContext = nullptr;
238  bool ShouldInternalize = EnableLTOInternalization;
239  bool ShouldEmbedUselists = false;
240  bool ShouldRestoreGlobalsLinkage = false;
242  std::unique_ptr<ToolOutputFile> DiagnosticOutputFile;
243  bool Freestanding = false;
244 };
245 }
246 #endif
This class represents lattice values for constants.
Definition: AllocatorList.h:23
LLVMContext & getContext()
std::unique_ptr< MemoryBuffer > compileOptimized()
Compiles the merged optimized module into a single output file.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:116
bool addModule(struct LTOModule *)
Merge given module.
bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Optimizes the merged module.
void setShouldRestoreGlobalsLinkage(bool Value)
Restore linkage of globals.
void setAttr(StringRef MAttr)
std::unique_ptr< MemoryBuffer > compile(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
As with compile_to_file(), this function compiles the merged module into single output file...
void setFileType(TargetMachine::CodeGenFileType FT)
Set the file type to be emitted (assembly or object code).
bool writeMergedModules(StringRef Path)
Write the merged module to the file specified by the given path.
static const char * getVersionString()
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
lto_debug_model
Definition: lto.h:77
void setShouldEmbedUselists(bool Value)
void setCodePICModel(Optional< Reloc::Model > Model)
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:64
void setOptLevel(unsigned OptLevel)
void setTargetOptions(const TargetOptions &Options)
void setShouldInternalize(bool Value)
C++ class which implements the opaque lto_module_t type.
Definition: LTOModule.h:37
void setCodeGenDebugOptions(StringRef Opts)
Pass options to the driver and optimization passes.
llvm::cl::opt< bool > EnableLTOInternalization
Enable global value internalization in LTO.
C++ class which implements the opaque lto_code_gen_t type.
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition: lto.h:321
void setCpu(StringRef MCpu)
Module.h This file contains the declarations for the Module class.
static bool Enabled
Definition: Statistic.cpp:50
Target - Wrapper for Target specific information.
void addMustPreserveSymbol(StringRef Sym)
void DiagnosticHandler(const DiagnosticInfo &DI)
bool compile_to_file(const char **Name, bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Compile the merged module into a single output file; the path to output file is returned to the calle...
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
void setAsmUndefinedRefs(struct LTOModule *)
LLVM Value Representation.
Definition: Value.h:72
LTOCodeGenerator(LLVMContext &Context)
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:27
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
void parseCodeGenDebugOptions()
Parse the options set in setCodeGenDebugOptions.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit...
void setModule(std::unique_ptr< LTOModule > M)
Set the destination module.
void setFreestanding(bool Enabled)
Enable the Freestanding mode: indicate that the optimizer should not assume builtins are present on t...
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
void setDebugInfo(lto_debug_model)