lto: Clean up C libLTO interfaces pertaining to linker flags.
[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/ADT/STLExtras.h"
17 #include "llvm/CodeGen/CommandFlags.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/LTO/LTOCodeGenerator.h"
20 #include "llvm/LTO/LTOModule.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/Signals.h"
23 #include "llvm/Support/TargetSelect.h"
24
25 // extra command-line flags needed for LTOCodeGenerator
26 static cl::opt<char>
27 OptLevel("O",
28          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
29                   "(default = '-O2')"),
30          cl::Prefix,
31          cl::ZeroOrMore,
32          cl::init('2'));
33
34 static cl::opt<bool>
35 DisableInline("disable-inlining", cl::init(false),
36   cl::desc("Do not run the inliner pass"));
37
38 static cl::opt<bool>
39 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
40   cl::desc("Do not run the GVN load PRE pass"));
41
42 static cl::opt<bool>
43 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
44   cl::desc("Do not run loop or slp vectorization during LTO"));
45
46 // Holds most recent error string.
47 // *** Not thread safe ***
48 static std::string sLastErrorString;
49
50 // Holds the initialization state of the LTO module.
51 // *** Not thread safe ***
52 static bool initialized = false;
53
54 // Holds the command-line option parsing state of the LTO module.
55 static bool parsedOptions = false;
56
57 // Initialize the configured targets if they have not been initialized.
58 static void lto_initialize() {
59   if (!initialized) {
60 #ifdef LLVM_ON_WIN32
61     // Dialog box on crash disabling doesn't work across DLL boundaries, so do
62     // it here.
63     llvm::sys::DisableSystemDialogsOnCrash();
64 #endif
65
66     InitializeAllTargetInfos();
67     InitializeAllTargets();
68     InitializeAllTargetMCs();
69     InitializeAllAsmParsers();
70     InitializeAllAsmPrinters();
71     InitializeAllDisassemblers();
72     initialized = true;
73   }
74 }
75
76 namespace {
77
78 // This derived class owns the native object file. This helps implement the
79 // libLTO API semantics, which require that the code generator owns the object
80 // file.
81 struct LibLTOCodeGenerator : LTOCodeGenerator {
82   LibLTOCodeGenerator() {}
83   LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
84       : LTOCodeGenerator(std::move(Context)) {}
85
86   std::unique_ptr<MemoryBuffer> NativeObjectFile;
87 };
88
89 }
90
91 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
92 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
93
94 // Convert the subtarget features into a string to pass to LTOCodeGenerator.
95 static void lto_add_attrs(lto_code_gen_t cg) {
96   LTOCodeGenerator *CG = unwrap(cg);
97   if (MAttrs.size()) {
98     std::string attrs;
99     for (unsigned i = 0; i < MAttrs.size(); ++i) {
100       if (i > 0)
101         attrs.append(",");
102       attrs.append(MAttrs[i]);
103     }
104
105     CG->setAttr(attrs.c_str());
106   }
107
108   if (OptLevel < '0' || OptLevel > '3')
109     report_fatal_error("Optimization level must be between 0 and 3");
110   CG->setOptLevel(OptLevel - '0');
111 }
112
113 extern const char* lto_get_version() {
114   return LTOCodeGenerator::getVersionString();
115 }
116
117 const char* lto_get_error_message() {
118   return sLastErrorString.c_str();
119 }
120
121 bool lto_module_is_object_file(const char* path) {
122   return LTOModule::isBitcodeFile(path);
123 }
124
125 bool lto_module_is_object_file_for_target(const char* path,
126                                           const char* target_triplet_prefix) {
127   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path);
128   if (!Buffer)
129     return false;
130   return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix);
131 }
132
133 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
134   return LTOModule::isBitcodeFile(mem, length);
135 }
136
137 bool
138 lto_module_is_object_file_in_memory_for_target(const void* mem,
139                                             size_t length,
140                                             const char* target_triplet_prefix) {
141   std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
142   if (!buffer)
143     return false;
144   return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix);
145 }
146
147 lto_module_t lto_module_create(const char* path) {
148   lto_initialize();
149   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
150   return wrap(LTOModule::createFromFile(path, Options, sLastErrorString));
151 }
152
153 lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
154   lto_initialize();
155   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
156   return wrap(
157       LTOModule::createFromOpenFile(fd, path, size, Options, sLastErrorString));
158 }
159
160 lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
161                                                  size_t file_size,
162                                                  size_t map_size,
163                                                  off_t offset) {
164   lto_initialize();
165   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
166   return wrap(LTOModule::createFromOpenFileSlice(fd, path, map_size, offset,
167                                                  Options, sLastErrorString));
168 }
169
170 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
171   lto_initialize();
172   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
173   return wrap(LTOModule::createFromBuffer(mem, length, Options, sLastErrorString));
174 }
175
176 lto_module_t lto_module_create_from_memory_with_path(const void* mem,
177                                                      size_t length,
178                                                      const char *path) {
179   lto_initialize();
180   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
181   return wrap(
182       LTOModule::createFromBuffer(mem, length, Options, sLastErrorString, path));
183 }
184
185 lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
186                                                 const char *path) {
187   lto_initialize();
188   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
189   return wrap(LTOModule::createInLocalContext(mem, length, Options,
190                                               sLastErrorString, path));
191 }
192
193 lto_module_t lto_module_create_in_codegen_context(const void *mem,
194                                                   size_t length,
195                                                   const char *path,
196                                                   lto_code_gen_t cg) {
197   lto_initialize();
198   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
199   return wrap(LTOModule::createInContext(mem, length, Options, sLastErrorString,
200                                          path, &unwrap(cg)->getContext()));
201 }
202
203 void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
204
205 const char* lto_module_get_target_triple(lto_module_t mod) {
206   return unwrap(mod)->getTargetTriple().c_str();
207 }
208
209 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
210   return unwrap(mod)->setTargetTriple(triple);
211 }
212
213 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
214   return unwrap(mod)->getSymbolCount();
215 }
216
217 const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
218   return unwrap(mod)->getSymbolName(index);
219 }
220
221 lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
222                                                       unsigned int index) {
223   return unwrap(mod)->getSymbolAttributes(index);
224 }
225
226 const char* lto_module_get_linkeropts(lto_module_t mod) {
227   return unwrap(mod)->getLinkerOpts();
228 }
229
230 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
231                                         lto_diagnostic_handler_t diag_handler,
232                                         void *ctxt) {
233   unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
234 }
235
236 static lto_code_gen_t createCodeGen(bool InLocalContext) {
237   lto_initialize();
238
239   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
240
241   LibLTOCodeGenerator *CodeGen =
242       InLocalContext ? new LibLTOCodeGenerator(make_unique<LLVMContext>())
243                      : new LibLTOCodeGenerator();
244   CodeGen->setTargetOptions(Options);
245   return wrap(CodeGen);
246 }
247
248 lto_code_gen_t lto_codegen_create(void) {
249   return createCodeGen(/* InLocalContext */ false);
250 }
251
252 lto_code_gen_t lto_codegen_create_in_local_context(void) {
253   return createCodeGen(/* InLocalContext */ true);
254 }
255
256 void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
257
258 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
259   return !unwrap(cg)->addModule(unwrap(mod));
260 }
261
262 void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
263   unwrap(cg)->setModule(unwrap(mod));
264 }
265
266 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
267   unwrap(cg)->setDebugInfo(debug);
268   return false;
269 }
270
271 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
272   unwrap(cg)->setCodePICModel(model);
273   return false;
274 }
275
276 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
277   return unwrap(cg)->setCpu(cpu);
278 }
279
280 void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
281   // In here only for backwards compatibility. We use MC now.
282 }
283
284 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
285                                     int nargs) {
286   // In here only for backwards compatibility. We use MC now.
287 }
288
289 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
290                                           const char *symbol) {
291   unwrap(cg)->addMustPreserveSymbol(symbol);
292 }
293
294 static void maybeParseOptions(lto_code_gen_t cg) {
295   if (!parsedOptions) {
296     unwrap(cg)->parseCodeGenDebugOptions();
297     lto_add_attrs(cg);
298     parsedOptions = true;
299   }
300 }
301
302 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
303   maybeParseOptions(cg);
304   return !unwrap(cg)->writeMergedModules(path, sLastErrorString);
305 }
306
307 const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
308   maybeParseOptions(cg);
309   LibLTOCodeGenerator *CG = unwrap(cg);
310   CG->NativeObjectFile = CG->compile(DisableInline, DisableGVNLoadPRE,
311                                      DisableLTOVectorization, sLastErrorString);
312   if (!CG->NativeObjectFile)
313     return nullptr;
314   *length = CG->NativeObjectFile->getBufferSize();
315   return CG->NativeObjectFile->getBufferStart();
316 }
317
318 bool lto_codegen_optimize(lto_code_gen_t cg) {
319   maybeParseOptions(cg);
320   return !unwrap(cg)->optimize(DisableInline,
321                                DisableGVNLoadPRE, DisableLTOVectorization,
322                                sLastErrorString);
323 }
324
325 const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
326   maybeParseOptions(cg);
327   LibLTOCodeGenerator *CG = unwrap(cg);
328   CG->NativeObjectFile = CG->compileOptimized(sLastErrorString);
329   if (!CG->NativeObjectFile)
330     return nullptr;
331   *length = CG->NativeObjectFile->getBufferSize();
332   return CG->NativeObjectFile->getBufferStart();
333 }
334
335 bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
336   maybeParseOptions(cg);
337   return !unwrap(cg)->compile_to_file(
338       name, DisableInline, DisableGVNLoadPRE,
339       DisableLTOVectorization, sLastErrorString);
340 }
341
342 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
343   unwrap(cg)->setCodeGenDebugOptions(opt);
344 }
345
346 unsigned int lto_api_version() { return LTO_API_VERSION; }
347
348 void lto_codegen_set_should_internalize(lto_code_gen_t cg,
349                                         bool ShouldInternalize) {
350   unwrap(cg)->setShouldInternalize(ShouldInternalize);
351 }
352
353 void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
354                                            lto_bool_t ShouldEmbedUselists) {
355   unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);
356 }