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"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include <string>
49 #include <vector>
50 
51 /// Enable global value internalization in LTO.
52 extern llvm::cl::opt<bool> EnableLTOInternalization;
53 
54 namespace llvm {
55 template <typename T> class ArrayRef;
56   class LLVMContext;
57   class DiagnosticInfo;
58   class Linker;
59   class Mangler;
60   class MemoryBuffer;
61   class TargetLibraryInfo;
62   class TargetMachine;
63   class raw_ostream;
64   class raw_pwrite_stream;
65 
66 //===----------------------------------------------------------------------===//
67 /// C++ class which implements the opaque lto_code_gen_t type.
68 ///
69 struct LTOCodeGenerator {
70   static const char *getVersionString();
71 
72   LTOCodeGenerator(LLVMContext &Context);
73   ~LTOCodeGenerator();
74 
75   /// Merge given module.  Return true on success.
76   ///
77   /// Resets \a HasVerifiedInput.
78   bool addModule(struct LTOModule *);
79 
80   /// Set the destination module.
81   ///
82   /// Resets \a HasVerifiedInput.
83   void setModule(std::unique_ptr<LTOModule> M);
84 
85   void setAsmUndefinedRefs(struct LTOModule *);
86   void setTargetOptions(const TargetOptions &Options);
87   void setDebugInfo(lto_debug_model);
setCodePICModelLTOCodeGenerator88   void setCodePICModel(Optional<Reloc::Model> Model) { RelocModel = Model; }
89 
90   /// Set the file type to be emitted (assembly or object code).
91   /// The default is TargetMachine::CGFT_ObjectFile.
setFileTypeLTOCodeGenerator92   void setFileType(TargetMachine::CodeGenFileType FT) { FileType = FT; }
93 
setCpuLTOCodeGenerator94   void setCpu(StringRef MCpu) { this->MCpu = MCpu; }
setAttrLTOCodeGenerator95   void setAttr(StringRef MAttr) { this->MAttr = MAttr; }
96   void setOptLevel(unsigned OptLevel);
97 
setShouldInternalizeLTOCodeGenerator98   void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
setShouldEmbedUselistsLTOCodeGenerator99   void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }
100 
101   /// Restore linkage of globals
102   ///
103   /// When set, the linkage of globals will be restored prior to code
104   /// generation. That is, a global symbol that had external linkage prior to
105   /// LTO will be emitted with external linkage again; and a local will remain
106   /// local. Note that this option only affects the end result - globals may
107   /// still be internalized in the process of LTO and may be modified and/or
108   /// deleted where legal.
109   ///
110   /// The default behavior will internalize globals (unless on the preserve
111   /// list) and, if parallel code generation is enabled, will externalize
112   /// all locals.
setShouldRestoreGlobalsLinkageLTOCodeGenerator113   void setShouldRestoreGlobalsLinkage(bool Value) {
114     ShouldRestoreGlobalsLinkage = Value;
115   }
116 
addMustPreserveSymbolLTOCodeGenerator117   void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols[Sym] = 1; }
118 
119   /// Pass options to the driver and optimization passes.
120   ///
121   /// These options are not necessarily for debugging purpose (the function
122   /// name is misleading).  This function should be called before
123   /// LTOCodeGenerator::compilexxx(), and
124   /// LTOCodeGenerator::writeMergedModules().
125   void setCodeGenDebugOptions(StringRef Opts);
126 
127   /// Parse the options set in setCodeGenDebugOptions.
128   ///
129   /// Like \a setCodeGenDebugOptions(), this must be called before
130   /// LTOCodeGenerator::compilexxx() and
131   /// LTOCodeGenerator::writeMergedModules().
132   void parseCodeGenDebugOptions();
133 
134   /// Write the merged module to the file specified by the given path.  Return
135   /// true on success.
136   ///
137   /// Calls \a verifyMergedModuleOnce().
138   bool writeMergedModules(StringRef Path);
139 
140   /// Compile the merged module into a *single* output file; the path to output
141   /// file is returned to the caller via argument "name". Return true on
142   /// success.
143   ///
144   /// \note It is up to the linker to remove the intermediate output file.  Do
145   /// not try to remove the object file in LTOCodeGenerator's destructor as we
146   /// don't who (LTOCodeGenerator or the output file) will last longer.
147   bool compile_to_file(const char **Name, bool DisableVerify,
148                        bool DisableInline, bool DisableGVNLoadPRE,
149                        bool DisableVectorization);
150 
151   /// As with compile_to_file(), this function compiles the merged module into
152   /// single output file. Instead of returning the output file path to the
153   /// caller (linker), it brings the output to a buffer, and returns the buffer
154   /// to the caller. This function should delete the intermediate file once
155   /// its content is brought to memory. Return NULL if the compilation was not
156   /// successful.
157   std::unique_ptr<MemoryBuffer> compile(bool DisableVerify, bool DisableInline,
158                                         bool DisableGVNLoadPRE,
159                                         bool DisableVectorization);
160 
161   /// Optimizes the merged module.  Returns true on success.
162   ///
163   /// Calls \a verifyMergedModuleOnce().
164   bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE,
165                 bool DisableVectorization);
166 
167   /// Compiles the merged optimized module into a single output file. It brings
168   /// the output to a buffer, and returns the buffer to the caller. Return NULL
169   /// if the compilation was not successful.
170   std::unique_ptr<MemoryBuffer> compileOptimized();
171 
172   /// Compile the merged optimized module into out.size() output files each
173   /// representing a linkable partition of the module. If out contains more
174   /// than one element, code generation is done in parallel with out.size()
175   /// threads.  Output files will be written to members of out. Returns true on
176   /// success.
177   ///
178   /// Calls \a verifyMergedModuleOnce().
179   bool compileOptimized(ArrayRef<raw_pwrite_stream *> Out);
180 
181   /// Enable the Freestanding mode: indicate that the optimizer should not
182   /// assume builtins are present on the target.
setFreestandingLTOCodeGenerator183   void setFreestanding(bool Enabled) { Freestanding = Enabled; }
184 
185   void setDiagnosticHandler(lto_diagnostic_handler_t, void *);
186 
getContextLTOCodeGenerator187   LLVMContext &getContext() { return Context; }
188 
resetMergedModuleLTOCodeGenerator189   void resetMergedModule() { MergedModule.reset(); }
190   void DiagnosticHandler(const DiagnosticInfo &DI);
191 
192 private:
193   void initializeLTOPasses();
194 
195   /// Verify the merged module on first call.
196   ///
197   /// Sets \a HasVerifiedInput on first call and doesn't run again on the same
198   /// input.
199   void verifyMergedModuleOnce();
200 
201   bool compileOptimizedToFile(const char **Name);
202   void restoreLinkageForExternals();
203   void applyScopeRestrictions();
204   void preserveDiscardableGVs(
205       Module &TheModule,
206       llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV);
207 
208   bool determineTarget();
209   std::unique_ptr<TargetMachine> createTargetMachine();
210 
211   void emitError(const std::string &ErrMsg);
212   void emitWarning(const std::string &ErrMsg);
213 
214   void finishOptimizationRemarks();
215 
216   LLVMContext &Context;
217   std::unique_ptr<Module> MergedModule;
218   std::unique_ptr<Linker> TheLinker;
219   std::unique_ptr<TargetMachine> TargetMach;
220   bool EmitDwarfDebugInfo = false;
221   bool ScopeRestrictionsDone = false;
222   bool HasVerifiedInput = false;
223   Optional<Reloc::Model> RelocModel;
224   StringSet<> MustPreserveSymbols;
225   StringSet<> AsmUndefinedRefs;
226   StringMap<GlobalValue::LinkageTypes> ExternalSymbols;
227   std::vector<std::string> CodegenOptions;
228   std::string FeatureStr;
229   std::string MCpu;
230   std::string MAttr;
231   std::string NativeObjectPath;
232   TargetOptions Options;
233   CodeGenOpt::Level CGOptLevel = CodeGenOpt::Default;
234   const Target *MArch = nullptr;
235   std::string TripleStr;
236   unsigned OptLevel = 2;
237   lto_diagnostic_handler_t DiagHandler = nullptr;
238   void *DiagContext = nullptr;
239   bool ShouldInternalize = EnableLTOInternalization;
240   bool ShouldEmbedUselists = false;
241   bool ShouldRestoreGlobalsLinkage = false;
242   TargetMachine::CodeGenFileType FileType = TargetMachine::CGFT_ObjectFile;
243   std::unique_ptr<ToolOutputFile> DiagnosticOutputFile;
244   bool Freestanding = false;
245 };
246 }
247 #endif
248