e55708c70f89158ed1ca08bb0af3945866122bf7
[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 unsigned int lto_module_get_num_deplibs(lto_module_t mod) {
227   return unwrap(mod)->getDependentLibraryCount();
228 }
229
230 const char* lto_module_get_deplib(lto_module_t mod, unsigned int index) {
231   return unwrap(mod)->getDependentLibrary(index);
232 }
233
234 unsigned int lto_module_get_num_linkeropts(lto_module_t mod) {
235   return unwrap(mod)->getLinkerOptCount();
236 }
237
238 const char* lto_module_get_linkeropt(lto_module_t mod, unsigned int index) {
239   return unwrap(mod)->getLinkerOpt(index);
240 }
241
242 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
243                                         lto_diagnostic_handler_t diag_handler,
244                                         void *ctxt) {
245   unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
246 }
247
248 static lto_code_gen_t createCodeGen(bool InLocalContext) {
249   lto_initialize();
250
251   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
252
253   LibLTOCodeGenerator *CodeGen =
254       InLocalContext ? new LibLTOCodeGenerator(make_unique<LLVMContext>())
255                      : new LibLTOCodeGenerator();
256   CodeGen->setTargetOptions(Options);
257   return wrap(CodeGen);
258 }
259
260 lto_code_gen_t lto_codegen_create(void) {
261   return createCodeGen(/* InLocalContext */ false);
262 }
263
264 lto_code_gen_t lto_codegen_create_in_local_context(void) {
265   return createCodeGen(/* InLocalContext */ true);
266 }
267
268 void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
269
270 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
271   return !unwrap(cg)->addModule(unwrap(mod));
272 }
273
274 void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
275   unwrap(cg)->setModule(unwrap(mod));
276 }
277
278 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
279   unwrap(cg)->setDebugInfo(debug);
280   return false;
281 }
282
283 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
284   unwrap(cg)->setCodePICModel(model);
285   return false;
286 }
287
288 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
289   return unwrap(cg)->setCpu(cpu);
290 }
291
292 void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
293   // In here only for backwards compatibility. We use MC now.
294 }
295
296 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
297                                     int nargs) {
298   // In here only for backwards compatibility. We use MC now.
299 }
300
301 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
302                                           const char *symbol) {
303   unwrap(cg)->addMustPreserveSymbol(symbol);
304 }
305
306 static void maybeParseOptions(lto_code_gen_t cg) {
307   if (!parsedOptions) {
308     unwrap(cg)->parseCodeGenDebugOptions();
309     lto_add_attrs(cg);
310     parsedOptions = true;
311   }
312 }
313
314 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
315   maybeParseOptions(cg);
316   return !unwrap(cg)->writeMergedModules(path, sLastErrorString);
317 }
318
319 const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
320   maybeParseOptions(cg);
321   LibLTOCodeGenerator *CG = unwrap(cg);
322   CG->NativeObjectFile = CG->compile(DisableInline, DisableGVNLoadPRE,
323                                      DisableLTOVectorization, sLastErrorString);
324   if (!CG->NativeObjectFile)
325     return nullptr;
326   *length = CG->NativeObjectFile->getBufferSize();
327   return CG->NativeObjectFile->getBufferStart();
328 }
329
330 bool lto_codegen_optimize(lto_code_gen_t cg) {
331   maybeParseOptions(cg);
332   return !unwrap(cg)->optimize(DisableInline,
333                                DisableGVNLoadPRE, DisableLTOVectorization,
334                                sLastErrorString);
335 }
336
337 const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
338   maybeParseOptions(cg);
339   LibLTOCodeGenerator *CG = unwrap(cg);
340   CG->NativeObjectFile = CG->compileOptimized(sLastErrorString);
341   if (!CG->NativeObjectFile)
342     return nullptr;
343   *length = CG->NativeObjectFile->getBufferSize();
344   return CG->NativeObjectFile->getBufferStart();
345 }
346
347 bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
348   maybeParseOptions(cg);
349   return !unwrap(cg)->compile_to_file(
350       name, DisableInline, DisableGVNLoadPRE,
351       DisableLTOVectorization, sLastErrorString);
352 }
353
354 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
355   unwrap(cg)->setCodeGenDebugOptions(opt);
356 }
357
358 unsigned int lto_api_version() { return LTO_API_VERSION; }
359
360 void lto_codegen_set_should_internalize(lto_code_gen_t cg,
361                                         bool ShouldInternalize) {
362   unwrap(cg)->setShouldInternalize(ShouldInternalize);
363 }
364
365 void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
366                                            lto_bool_t ShouldEmbedUselists) {
367   unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);
368 }