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