1 //===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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"
27 // extra command-line flags needed for LTOCodeGenerator
30 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
37 DisableInline("disable-inlining", cl::init(false),
38 cl::desc("Do not run the inliner pass"));
41 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
42 cl::desc("Do not run the GVN load PRE pass"));
45 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
46 cl::desc("Do not run loop or slp vectorization during LTO"));
49 static bool VerifyByDefault = false;
51 static bool VerifyByDefault = true;
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"));
58 // Holds most recent error string.
59 // *** Not thread safe ***
60 static std::string sLastErrorString;
62 // Holds the initialization state of the LTO module.
63 // *** Not thread safe ***
64 static bool initialized = false;
66 // Holds the command-line option parsing state of the LTO module.
67 static bool parsedOptions = false;
69 static LLVMContext *LTOContext = nullptr;
71 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
72 if (DI.getSeverity() != DS_Error) {
73 DiagnosticPrinterRawOStream DP(errs());
78 sLastErrorString = "";
80 raw_string_ostream Stream(sLastErrorString);
81 DiagnosticPrinterRawOStream DP(Stream);
84 sLastErrorString += '\n';
87 // Initialize the configured targets if they have not been initialized.
88 static void lto_initialize() {
91 // Dialog box on crash disabling doesn't work across DLL boundaries, so do
93 llvm::sys::DisableSystemDialogsOnCrash();
96 InitializeAllTargetInfos();
97 InitializeAllTargets();
98 InitializeAllTargetMCs();
99 InitializeAllAsmParsers();
100 InitializeAllAsmPrinters();
101 InitializeAllDisassemblers();
103 LTOContext = &getGlobalContext();
104 LTOContext->setDiagnosticHandler(diagnosticHandler, nullptr, true);
111 static void handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,
112 const char *Msg, void *) {
113 sLastErrorString = Msg;
114 sLastErrorString += "\n";
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
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); }
127 std::unique_ptr<MemoryBuffer> NativeObjectFile;
128 std::unique_ptr<LLVMContext> OwnedContext;
133 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
134 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
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);
141 for (unsigned i = 0; i < MAttrs.size(); ++i) {
144 attrs.append(MAttrs[i]);
147 CG->setAttr(attrs.c_str());
150 if (OptLevel < '0' || OptLevel > '3')
151 report_fatal_error("Optimization level must be between 0 and 3");
152 CG->setOptLevel(OptLevel - '0');
155 extern const char* lto_get_version() {
156 return LTOCodeGenerator::getVersionString();
159 const char* lto_get_error_message() {
160 return sLastErrorString.c_str();
163 bool lto_module_is_object_file(const char* path) {
164 return LTOModule::isBitcodeFile(path);
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);
172 return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix);
175 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
176 return LTOModule::isBitcodeFile(mem, length);
180 lto_module_is_object_file_in_memory_for_target(const void* mem,
182 const char* target_triplet_prefix) {
183 std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
186 return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix);
189 lto_module_t lto_module_create(const char* path) {
191 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
192 ErrorOr<std::unique_ptr<LTOModule>> M =
193 LTOModule::createFromFile(*LTOContext, path, Options);
196 return wrap(M->release());
199 lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
201 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
202 ErrorOr<std::unique_ptr<LTOModule>> M =
203 LTOModule::createFromOpenFile(*LTOContext, fd, path, size, Options);
206 return wrap(M->release());
209 lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
214 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
215 ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFileSlice(
216 *LTOContext, fd, path, map_size, offset, Options);
219 return wrap(M->release());
222 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
224 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
225 ErrorOr<std::unique_ptr<LTOModule>> M =
226 LTOModule::createFromBuffer(*LTOContext, mem, length, Options);
229 return wrap(M->release());
232 lto_module_t lto_module_create_from_memory_with_path(const void* mem,
236 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
237 ErrorOr<std::unique_ptr<LTOModule>> M =
238 LTOModule::createFromBuffer(*LTOContext, mem, length, Options, path);
241 return wrap(M->release());
244 lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
247 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
248 ErrorOr<std::unique_ptr<LTOModule>> M =
249 LTOModule::createInLocalContext(mem, length, Options, path);
252 return wrap(M->release());
255 lto_module_t lto_module_create_in_codegen_context(const void *mem,
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());
266 void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
268 const char* lto_module_get_target_triple(lto_module_t mod) {
269 return unwrap(mod)->getTargetTriple().c_str();
272 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
273 return unwrap(mod)->setTargetTriple(triple);
276 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
277 return unwrap(mod)->getSymbolCount();
280 const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
281 return unwrap(mod)->getSymbolName(index);
284 lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
285 unsigned int index) {
286 return unwrap(mod)->getSymbolAttributes(index);
289 const char* lto_module_get_linkeropts(lto_module_t mod) {
290 return unwrap(mod)->getLinkerOpts();
293 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
294 lto_diagnostic_handler_t diag_handler,
296 unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
299 static lto_code_gen_t createCodeGen(bool InLocalContext) {
302 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
304 LibLTOCodeGenerator *CodeGen =
305 InLocalContext ? new LibLTOCodeGenerator(make_unique<LLVMContext>())
306 : new LibLTOCodeGenerator();
307 CodeGen->setTargetOptions(Options);
308 return wrap(CodeGen);
311 lto_code_gen_t lto_codegen_create(void) {
312 return createCodeGen(/* InLocalContext */ false);
315 lto_code_gen_t lto_codegen_create_in_local_context(void) {
316 return createCodeGen(/* InLocalContext */ true);
319 void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
321 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
322 return !unwrap(cg)->addModule(unwrap(mod));
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)));
329 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
330 unwrap(cg)->setDebugInfo(debug);
334 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
336 case LTO_CODEGEN_PIC_MODEL_STATIC:
337 unwrap(cg)->setCodePICModel(Reloc::Static);
339 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
340 unwrap(cg)->setCodePICModel(Reloc::PIC_);
342 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
343 unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
345 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
346 unwrap(cg)->setCodePICModel(Reloc::Default);
349 sLastErrorString = "Unknown PIC model";
353 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
354 return unwrap(cg)->setCpu(cpu);
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.
361 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
363 // In here only for backwards compatibility. We use MC now.
366 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
367 const char *symbol) {
368 unwrap(cg)->addMustPreserveSymbol(symbol);
371 static void maybeParseOptions(lto_code_gen_t cg) {
372 if (!parsedOptions) {
373 unwrap(cg)->parseCodeGenDebugOptions();
375 parsedOptions = true;
379 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
380 maybeParseOptions(cg);
381 return !unwrap(cg)->writeMergedModules(path);
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)
392 *length = CG->NativeObjectFile->getBufferSize();
393 return CG->NativeObjectFile->getBufferStart();
396 bool lto_codegen_optimize(lto_code_gen_t cg) {
397 maybeParseOptions(cg);
398 return !unwrap(cg)->optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
399 DisableLTOVectorization);
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)
408 *length = CG->NativeObjectFile->getBufferSize();
409 return CG->NativeObjectFile->getBufferStart();
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);
419 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
420 unwrap(cg)->setCodeGenDebugOptions(opt);
423 unsigned int lto_api_version() { return LTO_API_VERSION; }
425 void lto_codegen_set_should_internalize(lto_code_gen_t cg,
426 bool ShouldInternalize) {
427 unwrap(cg)->setShouldInternalize(ShouldInternalize);
430 void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
431 lto_bool_t ShouldEmbedUselists) {
432 unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);