LTO API: add lto_module_create_from_memory_with_path.
[oota-llvm.git] / tools / lto / lto.cpp
1 //===-lto.cpp - 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 implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm-c/lto.h"
16 #include "llvm-c/Core.h"
17 #include "llvm-c/Target.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/LTO/LTOCodeGenerator.h"
20 #include "llvm/LTO/LTOModule.h"
21
22 // extra command-line flags needed for LTOCodeGenerator
23 static cl::opt<bool>
24 DisableOpt("disable-opt", cl::init(false),
25   cl::desc("Do not run any optimization passes"));
26
27 static cl::opt<bool>
28 DisableInline("disable-inlining", cl::init(false),
29   cl::desc("Do not run the inliner pass"));
30
31 static cl::opt<bool>
32 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
33   cl::desc("Do not run the GVN load PRE pass"));
34
35 // Holds most recent error string.
36 // *** Not thread safe ***
37 static std::string sLastErrorString;
38
39 // Holds the initialization state of the LTO module.
40 // *** Not thread safe ***
41 static bool initialized = false;
42
43 // Holds the command-line option parsing state of the LTO module.
44 static bool parsedOptions = false;
45
46 // Initialize the configured targets if they have not been initialized.
47 static void lto_initialize() {
48   if (!initialized) {
49     LLVMInitializeAllTargetInfos();
50     LLVMInitializeAllTargets();
51     LLVMInitializeAllTargetMCs();
52     LLVMInitializeAllAsmParsers();
53     LLVMInitializeAllAsmPrinters();
54     LLVMInitializeAllDisassemblers();
55     initialized = true;
56   }
57 }
58
59 static void lto_set_target_options(llvm::TargetOptions &Options) {
60   Options.LessPreciseFPMADOption = EnableFPMAD;
61   Options.NoFramePointerElim = DisableFPElim;
62   Options.AllowFPOpFusion = FuseFPOps;
63   Options.UnsafeFPMath = EnableUnsafeFPMath;
64   Options.NoInfsFPMath = EnableNoInfsFPMath;
65   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
66   Options.HonorSignDependentRoundingFPMathOption =
67     EnableHonorSignDependentRoundingFPMath;
68   Options.UseSoftFloat = GenerateSoftFloatCalls;
69   if (FloatABIForCalls != llvm::FloatABI::Default)
70     Options.FloatABIType = FloatABIForCalls;
71   Options.NoZerosInBSS = DontPlaceZerosInBSS;
72   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
73   Options.DisableTailCalls = DisableTailCalls;
74   Options.StackAlignmentOverride = OverrideStackAlignment;
75   Options.TrapFuncName = TrapFuncName;
76   Options.PositionIndependentExecutable = EnablePIE;
77   Options.EnableSegmentedStacks = SegmentedStacks;
78   Options.UseInitArray = UseInitArray;
79 }
80
81 /// lto_get_version - Returns a printable string.
82 extern const char* lto_get_version() {
83   return LTOCodeGenerator::getVersionString();
84 }
85
86 /// lto_get_error_message - Returns the last error string or NULL if last
87 /// operation was successful.
88 const char* lto_get_error_message() {
89   return sLastErrorString.c_str();
90 }
91
92 /// lto_module_is_object_file - Validates if a file is a loadable object file.
93 bool lto_module_is_object_file(const char* path) {
94   return LTOModule::isBitcodeFile(path);
95 }
96
97 /// lto_module_is_object_file_for_target - Validates if a file is a loadable
98 /// object file compilable for requested target.
99 bool lto_module_is_object_file_for_target(const char* path,
100                                           const char* target_triplet_prefix) {
101   return LTOModule::isBitcodeFileForTarget(path, target_triplet_prefix);
102 }
103
104 /// lto_module_is_object_file_in_memory - Validates if a buffer is a loadable
105 /// object file.
106 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
107   return LTOModule::isBitcodeFile(mem, length);
108 }
109
110 /// lto_module_is_object_file_in_memory_for_target - Validates if a buffer is a
111 /// loadable object file compilable for the target.
112 bool
113 lto_module_is_object_file_in_memory_for_target(const void* mem,
114                                             size_t length,
115                                             const char* target_triplet_prefix) {
116   return LTOModule::isBitcodeFileForTarget(mem, length, target_triplet_prefix);
117 }
118
119 /// lto_module_create - Loads an object file from disk. Returns NULL on error
120 /// (check lto_get_error_message() for details).
121 lto_module_t lto_module_create(const char* path) {
122   lto_initialize();
123   llvm::TargetOptions Options;
124   lto_set_target_options(Options);
125   return LTOModule::makeLTOModule(path, Options, sLastErrorString);
126 }
127
128 /// lto_module_create_from_fd - Loads an object file from disk. Returns NULL on
129 /// error (check lto_get_error_message() for details).
130 lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
131   lto_initialize();
132   llvm::TargetOptions Options;
133   lto_set_target_options(Options);
134   return LTOModule::makeLTOModule(fd, path, size, Options, sLastErrorString);
135 }
136
137 /// lto_module_create_from_fd_at_offset - Loads an object file from disk.
138 /// Returns NULL on error (check lto_get_error_message() for details).
139 lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
140                                                  size_t file_size,
141                                                  size_t map_size,
142                                                  off_t offset) {
143   lto_initialize();
144   llvm::TargetOptions Options;
145   lto_set_target_options(Options);
146   return LTOModule::makeLTOModule(fd, path, map_size, offset, Options,
147                                   sLastErrorString);
148 }
149
150 /// lto_module_create_from_memory - Loads an object file from memory. Returns
151 /// NULL on error (check lto_get_error_message() for details).
152 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
153   lto_initialize();
154   llvm::TargetOptions Options;
155   lto_set_target_options(Options);
156   return LTOModule::makeLTOModule(mem, length, Options, sLastErrorString);
157 }
158
159 /// Loads an object file from memory with an extra path argument.
160 /// Returns NULL on error (check lto_get_error_message() for details).
161 lto_module_t lto_module_create_from_memory_with_path(const void* mem,
162                                                      size_t length,
163                                                      const char *path) {
164   lto_initialize();
165   llvm::TargetOptions Options;
166   lto_set_target_options(Options);
167   return LTOModule::makeLTOModule(mem, length, Options, sLastErrorString, path);
168 }
169
170 /// lto_module_dispose - Frees all memory for a module. Upon return the
171 /// lto_module_t is no longer valid.
172 void lto_module_dispose(lto_module_t mod) {
173   delete mod;
174 }
175
176 /// lto_module_get_target_triple - Returns triplet string which the object
177 /// module was compiled under.
178 const char* lto_module_get_target_triple(lto_module_t mod) {
179   return mod->getTargetTriple();
180 }
181
182 /// lto_module_set_target_triple - Sets triple string with which the object will
183 /// be codegened.
184 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
185   return mod->setTargetTriple(triple);
186 }
187
188 /// lto_module_get_num_symbols - Returns the number of symbols in the object
189 /// module.
190 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
191   return mod->getSymbolCount();
192 }
193
194 /// lto_module_get_symbol_name - Returns the name of the ith symbol in the
195 /// object module.
196 const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
197   return mod->getSymbolName(index);
198 }
199
200 /// lto_module_get_symbol_attribute - Returns the attributes of the ith symbol
201 /// in the object module.
202 lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
203                                                       unsigned int index) {
204   return mod->getSymbolAttributes(index);
205 }
206
207 /// lto_module_get_num_deplibs - Returns the number of dependent libraries in
208 /// the object module.
209 unsigned int lto_module_get_num_deplibs(lto_module_t mod) {
210   return mod->getDependentLibraryCount();
211 }
212
213 /// lto_module_get_deplib - Returns the ith dependent library in the module.
214 const char* lto_module_get_deplib(lto_module_t mod, unsigned int index) {
215   return mod->getDependentLibrary(index);
216 }
217
218 /// lto_module_get_num_linkeropts - Returns the number of linker options in the
219 /// object module.
220 unsigned int lto_module_get_num_linkeropts(lto_module_t mod) {
221   return mod->getLinkerOptCount();
222 }
223
224 /// lto_module_get_linkeropt - Returns the ith linker option in the module.
225 const char* lto_module_get_linkeropt(lto_module_t mod, unsigned int index) {
226   return mod->getLinkerOpt(index);
227 }
228
229 /// Set a diagnostic handler.
230 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
231                                         lto_diagnostic_handler_t diag_handler,
232                                         void *ctxt) {
233   cg->setDiagnosticHandler(diag_handler, ctxt);
234 }
235
236 /// lto_codegen_create - Instantiates a code generator. Returns NULL if there
237 /// is an error.
238 lto_code_gen_t lto_codegen_create(void) {
239   lto_initialize();
240
241   TargetOptions Options;
242   lto_set_target_options(Options);
243
244   LTOCodeGenerator *CodeGen = new LTOCodeGenerator();
245   if (CodeGen)
246     CodeGen->setTargetOptions(Options);
247   return CodeGen;
248 }
249
250 /// lto_codegen_dispose - Frees all memory for a code generator. Upon return the
251 /// lto_code_gen_t is no longer valid.
252 void lto_codegen_dispose(lto_code_gen_t cg) {
253   delete cg;
254 }
255
256 /// lto_codegen_add_module - Add an object module to the set of modules for
257 /// which code will be generated. Returns true on error (check
258 /// lto_get_error_message() for details).
259 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
260   return !cg->addModule(mod, sLastErrorString);
261 }
262
263 /// lto_codegen_set_debug_model - Sets what if any format of debug info should
264 /// be generated. Returns true on error (check lto_get_error_message() for
265 /// details).
266 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
267   cg->setDebugInfo(debug);
268   return false;
269 }
270
271 /// lto_codegen_set_pic_model - Sets what code model to generated. Returns true
272 /// on error (check lto_get_error_message() for details).
273 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
274   cg->setCodePICModel(model);
275   return false;
276 }
277
278 /// lto_codegen_set_cpu - Sets the cpu to generate code for.
279 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
280   return cg->setCpu(cpu);
281 }
282
283 /// lto_codegen_set_assembler_path - Sets the path to the assembler tool.
284 void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
285   // In here only for backwards compatibility. We use MC now.
286 }
287
288 /// lto_codegen_set_assembler_args - Sets extra arguments that libLTO should
289 /// pass to the assembler.
290 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
291                                     int nargs) {
292   // In here only for backwards compatibility. We use MC now.
293 }
294
295 /// lto_codegen_set_internalize_strategy - Sets the strategy to use during
296 /// internalize.
297 void lto_codegen_set_internalize_strategy(lto_code_gen_t cg,
298                                           lto_internalize_strategy strategy) {
299   cg->setInternalizeStrategy(strategy);
300 }
301
302 /// lto_codegen_add_must_preserve_symbol - Adds to a list of all global symbols
303 /// that must exist in the final generated code. If a function is not listed
304 /// there, it might be inlined into every usage and optimized away.
305 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
306                                           const char *symbol) {
307   cg->addMustPreserveSymbol(symbol);
308 }
309
310 /// lto_codegen_write_merged_modules - Writes a new file at the specified path
311 /// that contains the merged contents of all modules added so far. Returns true
312 /// on error (check lto_get_error_message() for details).
313 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
314   if (!parsedOptions) {
315     cg->parseCodeGenDebugOptions();
316     parsedOptions = true;
317   }
318   return !cg->writeMergedModules(path, sLastErrorString);
319 }
320
321 /// lto_codegen_compile - Generates code for all added modules into one native
322 /// object file. On success returns a pointer to a generated mach-o/ELF buffer
323 /// and length set to the buffer size. The buffer is owned by the lto_code_gen_t
324 /// object and will be freed when lto_codegen_dispose() is called, or
325 /// lto_codegen_compile() is called again. On failure, returns NULL (check
326 /// lto_get_error_message() for details).
327 const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
328   if (!parsedOptions) {
329     cg->parseCodeGenDebugOptions();
330     parsedOptions = true;
331   }
332   return cg->compile(length, DisableOpt, DisableInline, DisableGVNLoadPRE,
333                      sLastErrorString);
334 }
335
336 /// lto_codegen_compile_to_file - Generates code for all added modules into one
337 /// native object file. The name of the file is written to name. Returns true on
338 /// error.
339 bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
340   if (!parsedOptions) {
341     cg->parseCodeGenDebugOptions();
342     parsedOptions = true;
343   }
344   return !cg->compile_to_file(name, DisableOpt, DisableInline, DisableGVNLoadPRE,
345                               sLastErrorString);
346 }
347
348 /// lto_codegen_debug_options - Used to pass extra options to the code
349 /// generator.
350 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
351   cg->setCodeGenDebugOptions(opt);
352 }