LLVM  4.0.0
LTOCodeGenerator.h
Go to the documentation of this file.
1 //===-LTOCodeGenerator.h - LLVM Link Time Optimizer -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the LTOCodeGenerator class.
11 //
12 // LTO compilation consists of three phases: Pre-IPO, IPO and Post-IPO.
13 //
14 // The Pre-IPO phase compiles source code into bitcode file. The resulting
15 // bitcode files, along with object files and libraries, will be fed to the
16 // linker to through the IPO and Post-IPO phases. By using obj-file extension,
17 // the resulting bitcode file disguises itself as an object file, and therefore
18 // obviates the need of writing a special set of the make-rules only for LTO
19 // compilation.
20 //
21 // The IPO phase perform inter-procedural analyses and optimizations, and
22 // the Post-IPO consists two sub-phases: intra-procedural scalar optimizations
23 // (SOPT), and intra-procedural target-dependent code generator (CG).
24 //
25 // As of this writing, we don't separate IPO and the Post-IPO SOPT. They
26 // are intermingled together, and are driven by a single pass manager (see
27 // PassManagerBuilder::populateLTOPassManager()).
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_LTOCODEGENERATOR_H
36 #define LLVM_LTO_LTOCODEGENERATOR_H
37 
38 #include "llvm-c/lto.h"
39 #include "llvm/ADT/SmallPtrSet.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"
47 #include <string>
48 #include <vector>
49 
50 namespace llvm {
51 template <typename T> class ArrayRef;
52  class LLVMContext;
53  class DiagnosticInfo;
54  class Linker;
55  class Mangler;
56  class MemoryBuffer;
57  class TargetLibraryInfo;
58  class TargetMachine;
59  class raw_ostream;
60  class raw_pwrite_stream;
61 
62 //===----------------------------------------------------------------------===//
63 /// C++ class which implements the opaque lto_code_gen_t type.
64 ///
66  static const char *getVersionString();
67 
68  LTOCodeGenerator(LLVMContext &Context);
70 
71  /// Merge given module. Return true on success.
72  ///
73  /// Resets \a HasVerifiedInput.
74  bool addModule(struct LTOModule *);
75 
76  /// Set the destination module.
77  ///
78  /// Resets \a HasVerifiedInput.
79  void setModule(std::unique_ptr<LTOModule> M);
80 
81  void setAsmUndefinedRefs(struct LTOModule *);
82  void setTargetOptions(const TargetOptions &Options);
85 
86  /// Set the file type to be emitted (assembly or object code).
87  /// The default is TargetMachine::CGFT_ObjectFile.
88  void setFileType(TargetMachine::CodeGenFileType FT) { FileType = FT; }
89 
90  void setCpu(StringRef MCpu) { this->MCpu = MCpu; }
91  void setAttr(StringRef MAttr) { this->MAttr = MAttr; }
92  void setOptLevel(unsigned OptLevel);
93 
94  void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
95  void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }
96 
97  /// Restore linkage of globals
98  ///
99  /// When set, the linkage of globals will be restored prior to code
100  /// generation. That is, a global symbol that had external linkage prior to
101  /// LTO will be emitted with external linkage again; and a local will remain
102  /// local. Note that this option only affects the end result - globals may
103  /// still be internalized in the process of LTO and may be modified and/or
104  /// deleted where legal.
105  ///
106  /// The default behavior will internalize globals (unless on the preserve
107  /// list) and, if parallel code generation is enabled, will externalize
108  /// all locals.
110  ShouldRestoreGlobalsLinkage = Value;
111  }
112 
113  void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols[Sym] = 1; }
114 
115  /// Pass options to the driver and optimization passes.
116  ///
117  /// These options are not necessarily for debugging purpose (the function
118  /// name is misleading). This function should be called before
119  /// LTOCodeGenerator::compilexxx(), and
120  /// LTOCodeGenerator::writeMergedModules().
122 
123  /// Parse the options set in setCodeGenDebugOptions.
124  ///
125  /// Like \a setCodeGenDebugOptions(), this must be called before
126  /// LTOCodeGenerator::compilexxx() and
127  /// LTOCodeGenerator::writeMergedModules().
129 
130  /// Write the merged module to the file specified by the given path. Return
131  /// true on success.
132  ///
133  /// Calls \a verifyMergedModuleOnce().
134  bool writeMergedModules(StringRef Path);
135 
136  /// Compile the merged module into a *single* output file; the path to output
137  /// file is returned to the caller via argument "name". Return true on
138  /// success.
139  ///
140  /// \note It is up to the linker to remove the intermediate output file. Do
141  /// not try to remove the object file in LTOCodeGenerator's destructor as we
142  /// don't who (LTOCodeGenerator or the output file) will last longer.
143  bool compile_to_file(const char **Name, bool DisableVerify,
144  bool DisableInline, bool DisableGVNLoadPRE,
145  bool DisableVectorization);
146 
147  /// As with compile_to_file(), this function compiles the merged module into
148  /// single output file. Instead of returning the output file path to the
149  /// caller (linker), it brings the output to a buffer, and returns the buffer
150  /// to the caller. This function should delete the intermediate file once
151  /// its content is brought to memory. Return NULL if the compilation was not
152  /// successful.
153  std::unique_ptr<MemoryBuffer> compile(bool DisableVerify, bool DisableInline,
154  bool DisableGVNLoadPRE,
155  bool DisableVectorization);
156 
157  /// Optimizes the merged module. Returns true on success.
158  ///
159  /// Calls \a verifyMergedModuleOnce().
160  bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE,
161  bool DisableVectorization);
162 
163  /// Compiles the merged optimized module into a single output file. It brings
164  /// the output to a buffer, and returns the buffer to the caller. Return NULL
165  /// if the compilation was not successful.
166  std::unique_ptr<MemoryBuffer> compileOptimized();
167 
168  /// Compile the merged optimized module into out.size() output files each
169  /// representing a linkable partition of the module. If out contains more
170  /// than one element, code generation is done in parallel with out.size()
171  /// threads. Output files will be written to members of out. Returns true on
172  /// success.
173  ///
174  /// Calls \a verifyMergedModuleOnce().
176 
178 
179  LLVMContext &getContext() { return Context; }
180 
181  void resetMergedModule() { MergedModule.reset(); }
182 
183 private:
184  void initializeLTOPasses();
185 
186  /// Verify the merged module on first call.
187  ///
188  /// Sets \a HasVerifiedInput on first call and doesn't run again on the same
189  /// input.
190  void verifyMergedModuleOnce();
191 
192  bool compileOptimizedToFile(const char **Name);
193  void restoreLinkageForExternals();
194  void applyScopeRestrictions();
195  void preserveDiscardableGVs(
196  Module &TheModule,
197  llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV);
198 
199  bool determineTarget();
200  std::unique_ptr<TargetMachine> createTargetMachine();
201 
202  static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context);
203 
204  void DiagnosticHandler2(const DiagnosticInfo &DI);
205 
206  void emitError(const std::string &ErrMsg);
207  void emitWarning(const std::string &ErrMsg);
208 
209  bool setupOptimizationRemarks();
210  void finishOptimizationRemarks();
211 
212  LLVMContext &Context;
213  std::unique_ptr<Module> MergedModule;
214  std::unique_ptr<Linker> TheLinker;
215  std::unique_ptr<TargetMachine> TargetMach;
216  bool EmitDwarfDebugInfo = false;
217  bool ScopeRestrictionsDone = false;
218  bool HasVerifiedInput = false;
219  Optional<Reloc::Model> RelocModel;
220  StringSet<> MustPreserveSymbols;
221  StringSet<> AsmUndefinedRefs;
222  StringMap<GlobalValue::LinkageTypes> ExternalSymbols;
223  std::vector<std::string> CodegenOptions;
224  std::string FeatureStr;
225  std::string MCpu;
226  std::string MAttr;
227  std::string NativeObjectPath;
228  TargetOptions Options;
230  const Target *MArch = nullptr;
231  std::string TripleStr;
232  unsigned OptLevel = 2;
233  lto_diagnostic_handler_t DiagHandler = nullptr;
234  void *DiagContext = nullptr;
235  bool ShouldInternalize = true;
236  bool ShouldEmbedUselists = false;
237  bool ShouldRestoreGlobalsLinkage = false;
239  std::unique_ptr<tool_output_file> DiagnosticOutputFile;
240 };
241 }
242 #endif
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:52
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:83
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:33
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:48
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:38
void setCodeGenDebugOptions(StringRef Opts)
Pass options to the driver and optimization passes.
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition: lto.h:321
C++ class which implements the opaque lto_code_gen_t type.
void setCpu(StringRef MCpu)
Module.h This file contains the declarations for the Module class.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:223
Target - Wrapper for Target specific information.
void addMustPreserveSymbol(StringRef Sym)
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...
void setAsmUndefinedRefs(struct LTOModule *)
LLVM Value Representation.
Definition: Value.h:71
LTOCodeGenerator(LLVMContext &Context)
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:23
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
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 setDiagnosticHandler(lto_diagnostic_handler_t, void *)
void setDebugInfo(lto_debug_model)