109467b48Spatrick //===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the Link Time Optimization library. This library is
1009467b48Spatrick // intended to be used by linker to optimize code at link time.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick
1409467b48Spatrick #include "llvm-c/lto.h"
1509467b48Spatrick #include "llvm/ADT/STLExtras.h"
1609467b48Spatrick #include "llvm/ADT/StringExtras.h"
1709467b48Spatrick #include "llvm/Bitcode/BitcodeReader.h"
18097a140dSpatrick #include "llvm/CodeGen/CommandFlags.h"
1909467b48Spatrick #include "llvm/IR/DiagnosticInfo.h"
2009467b48Spatrick #include "llvm/IR/DiagnosticPrinter.h"
2109467b48Spatrick #include "llvm/IR/LLVMContext.h"
2209467b48Spatrick #include "llvm/LTO/LTO.h"
2309467b48Spatrick #include "llvm/LTO/legacy/LTOCodeGenerator.h"
2409467b48Spatrick #include "llvm/LTO/legacy/LTOModule.h"
2509467b48Spatrick #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
2609467b48Spatrick #include "llvm/Support/MemoryBuffer.h"
2709467b48Spatrick #include "llvm/Support/Signals.h"
2809467b48Spatrick #include "llvm/Support/TargetSelect.h"
2909467b48Spatrick #include "llvm/Support/raw_ostream.h"
3009467b48Spatrick
31097a140dSpatrick using namespace llvm;
32097a140dSpatrick
33097a140dSpatrick static codegen::RegisterCodeGenFlags CGF;
34097a140dSpatrick
3509467b48Spatrick // extra command-line flags needed for LTOCodeGenerator
3609467b48Spatrick static cl::opt<char>
3709467b48Spatrick OptLevel("O",
3809467b48Spatrick cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
3909467b48Spatrick "(default = '-O2')"),
40*d415bd75Srobert cl::Prefix, cl::init('2'));
4109467b48Spatrick
4209467b48Spatrick static cl::opt<bool> EnableFreestanding(
4309467b48Spatrick "lto-freestanding", cl::init(false),
4409467b48Spatrick cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
4509467b48Spatrick
4609467b48Spatrick #ifdef NDEBUG
4709467b48Spatrick static bool VerifyByDefault = false;
4809467b48Spatrick #else
4909467b48Spatrick static bool VerifyByDefault = true;
5009467b48Spatrick #endif
5109467b48Spatrick
5209467b48Spatrick static cl::opt<bool> DisableVerify(
5309467b48Spatrick "disable-llvm-verifier", cl::init(!VerifyByDefault),
5409467b48Spatrick cl::desc("Don't run the LLVM verifier during the optimization pipeline"));
5509467b48Spatrick
5609467b48Spatrick // Holds most recent error string.
5709467b48Spatrick // *** Not thread safe ***
5809467b48Spatrick static std::string sLastErrorString;
5909467b48Spatrick
6009467b48Spatrick // Holds the initialization state of the LTO module.
6109467b48Spatrick // *** Not thread safe ***
6209467b48Spatrick static bool initialized = false;
6309467b48Spatrick
6473471bf0Spatrick // Represent the state of parsing command line debug options.
6573471bf0Spatrick static enum class OptParsingState {
6673471bf0Spatrick NotParsed, // Initial state.
6773471bf0Spatrick Early, // After lto_set_debug_options is called.
6873471bf0Spatrick Done // After maybeParseOptions is called.
6973471bf0Spatrick } optionParsingState = OptParsingState::NotParsed;
7009467b48Spatrick
7109467b48Spatrick static LLVMContext *LTOContext = nullptr;
7209467b48Spatrick
7309467b48Spatrick struct LTOToolDiagnosticHandler : public DiagnosticHandler {
handleDiagnosticsLTOToolDiagnosticHandler7409467b48Spatrick bool handleDiagnostics(const DiagnosticInfo &DI) override {
7509467b48Spatrick if (DI.getSeverity() != DS_Error) {
7609467b48Spatrick DiagnosticPrinterRawOStream DP(errs());
7709467b48Spatrick DI.print(DP);
7809467b48Spatrick errs() << '\n';
7909467b48Spatrick return true;
8009467b48Spatrick }
8109467b48Spatrick sLastErrorString = "";
8209467b48Spatrick {
8309467b48Spatrick raw_string_ostream Stream(sLastErrorString);
8409467b48Spatrick DiagnosticPrinterRawOStream DP(Stream);
8509467b48Spatrick DI.print(DP);
8609467b48Spatrick }
8709467b48Spatrick return true;
8809467b48Spatrick }
8909467b48Spatrick };
9009467b48Spatrick
9109467b48Spatrick // Initialize the configured targets if they have not been initialized.
lto_initialize()9209467b48Spatrick static void lto_initialize() {
9309467b48Spatrick if (!initialized) {
9409467b48Spatrick #ifdef _WIN32
9509467b48Spatrick // Dialog box on crash disabling doesn't work across DLL boundaries, so do
9609467b48Spatrick // it here.
9709467b48Spatrick llvm::sys::DisableSystemDialogsOnCrash();
9809467b48Spatrick #endif
9909467b48Spatrick
10009467b48Spatrick InitializeAllTargetInfos();
10109467b48Spatrick InitializeAllTargets();
10209467b48Spatrick InitializeAllTargetMCs();
10309467b48Spatrick InitializeAllAsmParsers();
10409467b48Spatrick InitializeAllAsmPrinters();
10509467b48Spatrick InitializeAllDisassemblers();
10609467b48Spatrick
10709467b48Spatrick static LLVMContext Context;
10809467b48Spatrick LTOContext = &Context;
10909467b48Spatrick LTOContext->setDiagnosticHandler(
11009467b48Spatrick std::make_unique<LTOToolDiagnosticHandler>(), true);
11109467b48Spatrick initialized = true;
11209467b48Spatrick }
11309467b48Spatrick }
11409467b48Spatrick
11509467b48Spatrick namespace {
11609467b48Spatrick
handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,const char * Msg,void *)11709467b48Spatrick static void handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,
11809467b48Spatrick const char *Msg, void *) {
11909467b48Spatrick sLastErrorString = Msg;
12009467b48Spatrick }
12109467b48Spatrick
12209467b48Spatrick // This derived class owns the native object file. This helps implement the
12309467b48Spatrick // libLTO API semantics, which require that the code generator owns the object
12409467b48Spatrick // file.
12509467b48Spatrick struct LibLTOCodeGenerator : LTOCodeGenerator {
LibLTOCodeGenerator__anone9590d240111::LibLTOCodeGenerator12609467b48Spatrick LibLTOCodeGenerator() : LTOCodeGenerator(*LTOContext) { init(); }
LibLTOCodeGenerator__anone9590d240111::LibLTOCodeGenerator12709467b48Spatrick LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
12809467b48Spatrick : LTOCodeGenerator(*Context), OwnedContext(std::move(Context)) {
12909467b48Spatrick init();
13009467b48Spatrick }
13109467b48Spatrick
13209467b48Spatrick // Reset the module first in case MergedModule is created in OwnedContext.
13309467b48Spatrick // Module must be destructed before its context gets destructed.
~LibLTOCodeGenerator__anone9590d240111::LibLTOCodeGenerator13409467b48Spatrick ~LibLTOCodeGenerator() { resetMergedModule(); }
13509467b48Spatrick
init__anone9590d240111::LibLTOCodeGenerator13609467b48Spatrick void init() { setDiagnosticHandler(handleLibLTODiagnostic, nullptr); }
13709467b48Spatrick
13809467b48Spatrick std::unique_ptr<MemoryBuffer> NativeObjectFile;
13909467b48Spatrick std::unique_ptr<LLVMContext> OwnedContext;
14009467b48Spatrick };
14109467b48Spatrick
14209467b48Spatrick }
14309467b48Spatrick
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator,lto_code_gen_t)14409467b48Spatrick DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
14509467b48Spatrick DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThinLTOCodeGenerator, thinlto_code_gen_t)
14609467b48Spatrick DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
14709467b48Spatrick
14809467b48Spatrick // Convert the subtarget features into a string to pass to LTOCodeGenerator.
14909467b48Spatrick static void lto_add_attrs(lto_code_gen_t cg) {
15009467b48Spatrick LTOCodeGenerator *CG = unwrap(cg);
15173471bf0Spatrick CG->setAttrs(codegen::getMAttrs());
15209467b48Spatrick
15309467b48Spatrick if (OptLevel < '0' || OptLevel > '3')
15409467b48Spatrick report_fatal_error("Optimization level must be between 0 and 3");
15509467b48Spatrick CG->setOptLevel(OptLevel - '0');
15609467b48Spatrick CG->setFreestanding(EnableFreestanding);
15773471bf0Spatrick CG->setDisableVerify(DisableVerify);
15809467b48Spatrick }
15909467b48Spatrick
lto_get_version()16009467b48Spatrick extern const char* lto_get_version() {
16109467b48Spatrick return LTOCodeGenerator::getVersionString();
16209467b48Spatrick }
16309467b48Spatrick
lto_get_error_message()16409467b48Spatrick const char* lto_get_error_message() {
16509467b48Spatrick return sLastErrorString.c_str();
16609467b48Spatrick }
16709467b48Spatrick
lto_module_is_object_file(const char * path)16809467b48Spatrick bool lto_module_is_object_file(const char* path) {
16909467b48Spatrick return LTOModule::isBitcodeFile(StringRef(path));
17009467b48Spatrick }
17109467b48Spatrick
lto_module_is_object_file_for_target(const char * path,const char * target_triplet_prefix)17209467b48Spatrick bool lto_module_is_object_file_for_target(const char* path,
17309467b48Spatrick const char* target_triplet_prefix) {
17409467b48Spatrick ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path);
17509467b48Spatrick if (!Buffer)
17609467b48Spatrick return false;
17709467b48Spatrick return LTOModule::isBitcodeForTarget(Buffer->get(),
17809467b48Spatrick StringRef(target_triplet_prefix));
17909467b48Spatrick }
18009467b48Spatrick
lto_module_has_objc_category(const void * mem,size_t length)18109467b48Spatrick bool lto_module_has_objc_category(const void *mem, size_t length) {
18209467b48Spatrick std::unique_ptr<MemoryBuffer> Buffer(LTOModule::makeBuffer(mem, length));
18309467b48Spatrick if (!Buffer)
18409467b48Spatrick return false;
18509467b48Spatrick LLVMContext Ctx;
18609467b48Spatrick ErrorOr<bool> Result = expectedToErrorOrAndEmitErrors(
18709467b48Spatrick Ctx, llvm::isBitcodeContainingObjCCategory(*Buffer));
18809467b48Spatrick return Result && *Result;
18909467b48Spatrick }
19009467b48Spatrick
lto_module_is_object_file_in_memory(const void * mem,size_t length)19109467b48Spatrick bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
19209467b48Spatrick return LTOModule::isBitcodeFile(mem, length);
19309467b48Spatrick }
19409467b48Spatrick
19509467b48Spatrick bool
lto_module_is_object_file_in_memory_for_target(const void * mem,size_t length,const char * target_triplet_prefix)19609467b48Spatrick lto_module_is_object_file_in_memory_for_target(const void* mem,
19709467b48Spatrick size_t length,
19809467b48Spatrick const char* target_triplet_prefix) {
19909467b48Spatrick std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
20009467b48Spatrick if (!buffer)
20109467b48Spatrick return false;
20209467b48Spatrick return LTOModule::isBitcodeForTarget(buffer.get(),
20309467b48Spatrick StringRef(target_triplet_prefix));
20409467b48Spatrick }
20509467b48Spatrick
lto_module_create(const char * path)20609467b48Spatrick lto_module_t lto_module_create(const char* path) {
20709467b48Spatrick lto_initialize();
20873471bf0Spatrick llvm::TargetOptions Options =
20973471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple());
21009467b48Spatrick ErrorOr<std::unique_ptr<LTOModule>> M =
21109467b48Spatrick LTOModule::createFromFile(*LTOContext, StringRef(path), Options);
21209467b48Spatrick if (!M)
21309467b48Spatrick return nullptr;
21409467b48Spatrick return wrap(M->release());
21509467b48Spatrick }
21609467b48Spatrick
lto_module_create_from_fd(int fd,const char * path,size_t size)21709467b48Spatrick lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
21809467b48Spatrick lto_initialize();
21973471bf0Spatrick llvm::TargetOptions Options =
22073471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple());
22109467b48Spatrick ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFile(
22209467b48Spatrick *LTOContext, fd, StringRef(path), size, Options);
22309467b48Spatrick if (!M)
22409467b48Spatrick return nullptr;
22509467b48Spatrick return wrap(M->release());
22609467b48Spatrick }
22709467b48Spatrick
lto_module_create_from_fd_at_offset(int fd,const char * path,size_t file_size,size_t map_size,off_t offset)22809467b48Spatrick lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
22909467b48Spatrick size_t file_size,
23009467b48Spatrick size_t map_size,
23109467b48Spatrick off_t offset) {
23209467b48Spatrick lto_initialize();
23373471bf0Spatrick llvm::TargetOptions Options =
23473471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple());
23509467b48Spatrick ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFileSlice(
23609467b48Spatrick *LTOContext, fd, StringRef(path), map_size, offset, Options);
23709467b48Spatrick if (!M)
23809467b48Spatrick return nullptr;
23909467b48Spatrick return wrap(M->release());
24009467b48Spatrick }
24109467b48Spatrick
lto_module_create_from_memory(const void * mem,size_t length)24209467b48Spatrick lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
24309467b48Spatrick lto_initialize();
24473471bf0Spatrick llvm::TargetOptions Options =
24573471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple());
24609467b48Spatrick ErrorOr<std::unique_ptr<LTOModule>> M =
24709467b48Spatrick LTOModule::createFromBuffer(*LTOContext, mem, length, Options);
24809467b48Spatrick if (!M)
24909467b48Spatrick return nullptr;
25009467b48Spatrick return wrap(M->release());
25109467b48Spatrick }
25209467b48Spatrick
lto_module_create_from_memory_with_path(const void * mem,size_t length,const char * path)25309467b48Spatrick lto_module_t lto_module_create_from_memory_with_path(const void* mem,
25409467b48Spatrick size_t length,
25509467b48Spatrick const char *path) {
25609467b48Spatrick lto_initialize();
25773471bf0Spatrick llvm::TargetOptions Options =
25873471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple());
25909467b48Spatrick ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
26009467b48Spatrick *LTOContext, mem, length, Options, StringRef(path));
26109467b48Spatrick if (!M)
26209467b48Spatrick return nullptr;
26309467b48Spatrick return wrap(M->release());
26409467b48Spatrick }
26509467b48Spatrick
lto_module_create_in_local_context(const void * mem,size_t length,const char * path)26609467b48Spatrick lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
26709467b48Spatrick const char *path) {
26809467b48Spatrick lto_initialize();
26973471bf0Spatrick llvm::TargetOptions Options =
27073471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple());
27109467b48Spatrick
27209467b48Spatrick // Create a local context. Ownership will be transferred to LTOModule.
27309467b48Spatrick std::unique_ptr<LLVMContext> Context = std::make_unique<LLVMContext>();
27409467b48Spatrick Context->setDiagnosticHandler(std::make_unique<LTOToolDiagnosticHandler>(),
27509467b48Spatrick true);
27609467b48Spatrick
27709467b48Spatrick ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createInLocalContext(
27809467b48Spatrick std::move(Context), mem, length, Options, StringRef(path));
27909467b48Spatrick if (!M)
28009467b48Spatrick return nullptr;
28109467b48Spatrick return wrap(M->release());
28209467b48Spatrick }
28309467b48Spatrick
lto_module_create_in_codegen_context(const void * mem,size_t length,const char * path,lto_code_gen_t cg)28409467b48Spatrick lto_module_t lto_module_create_in_codegen_context(const void *mem,
28509467b48Spatrick size_t length,
28609467b48Spatrick const char *path,
28709467b48Spatrick lto_code_gen_t cg) {
28809467b48Spatrick lto_initialize();
28973471bf0Spatrick llvm::TargetOptions Options =
29073471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple());
29109467b48Spatrick ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
29209467b48Spatrick unwrap(cg)->getContext(), mem, length, Options, StringRef(path));
293*d415bd75Srobert if (!M)
294*d415bd75Srobert return nullptr;
29509467b48Spatrick return wrap(M->release());
29609467b48Spatrick }
29709467b48Spatrick
lto_module_dispose(lto_module_t mod)29809467b48Spatrick void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
29909467b48Spatrick
lto_module_get_target_triple(lto_module_t mod)30009467b48Spatrick const char* lto_module_get_target_triple(lto_module_t mod) {
30109467b48Spatrick return unwrap(mod)->getTargetTriple().c_str();
30209467b48Spatrick }
30309467b48Spatrick
lto_module_set_target_triple(lto_module_t mod,const char * triple)30409467b48Spatrick void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
30509467b48Spatrick return unwrap(mod)->setTargetTriple(StringRef(triple));
30609467b48Spatrick }
30709467b48Spatrick
lto_module_get_num_symbols(lto_module_t mod)30809467b48Spatrick unsigned int lto_module_get_num_symbols(lto_module_t mod) {
30909467b48Spatrick return unwrap(mod)->getSymbolCount();
31009467b48Spatrick }
31109467b48Spatrick
lto_module_get_symbol_name(lto_module_t mod,unsigned int index)31209467b48Spatrick const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
31309467b48Spatrick return unwrap(mod)->getSymbolName(index).data();
31409467b48Spatrick }
31509467b48Spatrick
lto_module_get_symbol_attribute(lto_module_t mod,unsigned int index)31609467b48Spatrick lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
31709467b48Spatrick unsigned int index) {
31809467b48Spatrick return unwrap(mod)->getSymbolAttributes(index);
31909467b48Spatrick }
32009467b48Spatrick
lto_module_get_linkeropts(lto_module_t mod)32109467b48Spatrick const char* lto_module_get_linkeropts(lto_module_t mod) {
32209467b48Spatrick return unwrap(mod)->getLinkerOpts().data();
32309467b48Spatrick }
32409467b48Spatrick
lto_module_get_macho_cputype(lto_module_t mod,unsigned int * out_cputype,unsigned int * out_cpusubtype)325097a140dSpatrick lto_bool_t lto_module_get_macho_cputype(lto_module_t mod,
326097a140dSpatrick unsigned int *out_cputype,
327097a140dSpatrick unsigned int *out_cpusubtype) {
328097a140dSpatrick LTOModule *M = unwrap(mod);
329097a140dSpatrick Expected<uint32_t> CPUType = M->getMachOCPUType();
330097a140dSpatrick if (!CPUType) {
331097a140dSpatrick sLastErrorString = toString(CPUType.takeError());
332097a140dSpatrick return true;
333097a140dSpatrick }
334097a140dSpatrick *out_cputype = *CPUType;
335097a140dSpatrick
336097a140dSpatrick Expected<uint32_t> CPUSubType = M->getMachOCPUSubType();
337097a140dSpatrick if (!CPUSubType) {
338097a140dSpatrick sLastErrorString = toString(CPUSubType.takeError());
339097a140dSpatrick return true;
340097a140dSpatrick }
341097a140dSpatrick *out_cpusubtype = *CPUSubType;
342097a140dSpatrick
343097a140dSpatrick return false;
344097a140dSpatrick }
345097a140dSpatrick
lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,lto_diagnostic_handler_t diag_handler,void * ctxt)34609467b48Spatrick void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
34709467b48Spatrick lto_diagnostic_handler_t diag_handler,
34809467b48Spatrick void *ctxt) {
34909467b48Spatrick unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
35009467b48Spatrick }
35109467b48Spatrick
createCodeGen(bool InLocalContext)35209467b48Spatrick static lto_code_gen_t createCodeGen(bool InLocalContext) {
35309467b48Spatrick lto_initialize();
35409467b48Spatrick
35573471bf0Spatrick TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
35609467b48Spatrick
35709467b48Spatrick LibLTOCodeGenerator *CodeGen =
35809467b48Spatrick InLocalContext ? new LibLTOCodeGenerator(std::make_unique<LLVMContext>())
35909467b48Spatrick : new LibLTOCodeGenerator();
36009467b48Spatrick CodeGen->setTargetOptions(Options);
36109467b48Spatrick return wrap(CodeGen);
36209467b48Spatrick }
36309467b48Spatrick
lto_codegen_create(void)36409467b48Spatrick lto_code_gen_t lto_codegen_create(void) {
36509467b48Spatrick return createCodeGen(/* InLocalContext */ false);
36609467b48Spatrick }
36709467b48Spatrick
lto_codegen_create_in_local_context(void)36809467b48Spatrick lto_code_gen_t lto_codegen_create_in_local_context(void) {
36909467b48Spatrick return createCodeGen(/* InLocalContext */ true);
37009467b48Spatrick }
37109467b48Spatrick
lto_codegen_dispose(lto_code_gen_t cg)37209467b48Spatrick void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
37309467b48Spatrick
lto_codegen_add_module(lto_code_gen_t cg,lto_module_t mod)37409467b48Spatrick bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
37509467b48Spatrick return !unwrap(cg)->addModule(unwrap(mod));
37609467b48Spatrick }
37709467b48Spatrick
lto_codegen_set_module(lto_code_gen_t cg,lto_module_t mod)37809467b48Spatrick void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
37909467b48Spatrick unwrap(cg)->setModule(std::unique_ptr<LTOModule>(unwrap(mod)));
38009467b48Spatrick }
38109467b48Spatrick
lto_codegen_set_debug_model(lto_code_gen_t cg,lto_debug_model debug)38209467b48Spatrick bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
38309467b48Spatrick unwrap(cg)->setDebugInfo(debug);
38409467b48Spatrick return false;
38509467b48Spatrick }
38609467b48Spatrick
lto_codegen_set_pic_model(lto_code_gen_t cg,lto_codegen_model model)38709467b48Spatrick bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
38809467b48Spatrick switch (model) {
38909467b48Spatrick case LTO_CODEGEN_PIC_MODEL_STATIC:
39009467b48Spatrick unwrap(cg)->setCodePICModel(Reloc::Static);
39109467b48Spatrick return false;
39209467b48Spatrick case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
39309467b48Spatrick unwrap(cg)->setCodePICModel(Reloc::PIC_);
39409467b48Spatrick return false;
39509467b48Spatrick case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
39609467b48Spatrick unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
39709467b48Spatrick return false;
39809467b48Spatrick case LTO_CODEGEN_PIC_MODEL_DEFAULT:
399*d415bd75Srobert unwrap(cg)->setCodePICModel(std::nullopt);
40009467b48Spatrick return false;
40109467b48Spatrick }
40209467b48Spatrick sLastErrorString = "Unknown PIC model";
40309467b48Spatrick return true;
40409467b48Spatrick }
40509467b48Spatrick
lto_codegen_set_cpu(lto_code_gen_t cg,const char * cpu)40609467b48Spatrick void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
40709467b48Spatrick return unwrap(cg)->setCpu(cpu);
40809467b48Spatrick }
40909467b48Spatrick
lto_codegen_set_assembler_path(lto_code_gen_t cg,const char * path)41009467b48Spatrick void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
41109467b48Spatrick // In here only for backwards compatibility. We use MC now.
41209467b48Spatrick }
41309467b48Spatrick
lto_codegen_set_assembler_args(lto_code_gen_t cg,const char ** args,int nargs)41409467b48Spatrick void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
41509467b48Spatrick int nargs) {
41609467b48Spatrick // In here only for backwards compatibility. We use MC now.
41709467b48Spatrick }
41809467b48Spatrick
lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,const char * symbol)41909467b48Spatrick void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
42009467b48Spatrick const char *symbol) {
42109467b48Spatrick unwrap(cg)->addMustPreserveSymbol(symbol);
42209467b48Spatrick }
42309467b48Spatrick
maybeParseOptions(lto_code_gen_t cg)42409467b48Spatrick static void maybeParseOptions(lto_code_gen_t cg) {
42573471bf0Spatrick if (optionParsingState != OptParsingState::Done) {
42673471bf0Spatrick // Parse options if any were set by the lto_codegen_debug_options* function.
42709467b48Spatrick unwrap(cg)->parseCodeGenDebugOptions();
42809467b48Spatrick lto_add_attrs(cg);
42973471bf0Spatrick optionParsingState = OptParsingState::Done;
43009467b48Spatrick }
43109467b48Spatrick }
43209467b48Spatrick
lto_codegen_write_merged_modules(lto_code_gen_t cg,const char * path)43309467b48Spatrick bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
43409467b48Spatrick maybeParseOptions(cg);
43509467b48Spatrick return !unwrap(cg)->writeMergedModules(path);
43609467b48Spatrick }
43709467b48Spatrick
lto_codegen_compile(lto_code_gen_t cg,size_t * length)43809467b48Spatrick const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
43909467b48Spatrick maybeParseOptions(cg);
44009467b48Spatrick LibLTOCodeGenerator *CG = unwrap(cg);
44173471bf0Spatrick CG->NativeObjectFile = CG->compile();
44209467b48Spatrick if (!CG->NativeObjectFile)
44309467b48Spatrick return nullptr;
44409467b48Spatrick *length = CG->NativeObjectFile->getBufferSize();
44509467b48Spatrick return CG->NativeObjectFile->getBufferStart();
44609467b48Spatrick }
44709467b48Spatrick
lto_codegen_optimize(lto_code_gen_t cg)44809467b48Spatrick bool lto_codegen_optimize(lto_code_gen_t cg) {
44909467b48Spatrick maybeParseOptions(cg);
45073471bf0Spatrick return !unwrap(cg)->optimize();
45109467b48Spatrick }
45209467b48Spatrick
lto_codegen_compile_optimized(lto_code_gen_t cg,size_t * length)45309467b48Spatrick const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
45409467b48Spatrick maybeParseOptions(cg);
45509467b48Spatrick LibLTOCodeGenerator *CG = unwrap(cg);
45609467b48Spatrick CG->NativeObjectFile = CG->compileOptimized();
45709467b48Spatrick if (!CG->NativeObjectFile)
45809467b48Spatrick return nullptr;
45909467b48Spatrick *length = CG->NativeObjectFile->getBufferSize();
46009467b48Spatrick return CG->NativeObjectFile->getBufferStart();
46109467b48Spatrick }
46209467b48Spatrick
lto_codegen_compile_to_file(lto_code_gen_t cg,const char ** name)46309467b48Spatrick bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
46409467b48Spatrick maybeParseOptions(cg);
46573471bf0Spatrick return !unwrap(cg)->compile_to_file(name);
46673471bf0Spatrick }
46773471bf0Spatrick
lto_set_debug_options(const char * const * options,int number)46873471bf0Spatrick void lto_set_debug_options(const char *const *options, int number) {
46973471bf0Spatrick assert(optionParsingState == OptParsingState::NotParsed &&
47073471bf0Spatrick "option processing already happened");
47173471bf0Spatrick // Need to put each suboption in a null-terminated string before passing to
47273471bf0Spatrick // parseCommandLineOptions().
47373471bf0Spatrick std::vector<std::string> Options;
47473471bf0Spatrick for (int i = 0; i < number; ++i)
47573471bf0Spatrick Options.push_back(options[i]);
47673471bf0Spatrick
47773471bf0Spatrick llvm::parseCommandLineOptions(Options);
47873471bf0Spatrick optionParsingState = OptParsingState::Early;
47909467b48Spatrick }
48009467b48Spatrick
lto_codegen_debug_options(lto_code_gen_t cg,const char * opt)48109467b48Spatrick void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
48273471bf0Spatrick assert(optionParsingState != OptParsingState::Early &&
48373471bf0Spatrick "early option processing already happened");
484097a140dSpatrick SmallVector<StringRef, 4> Options;
48509467b48Spatrick for (std::pair<StringRef, StringRef> o = getToken(opt); !o.first.empty();
48609467b48Spatrick o = getToken(o.second))
487097a140dSpatrick Options.push_back(o.first);
48809467b48Spatrick
48909467b48Spatrick unwrap(cg)->setCodeGenDebugOptions(Options);
49009467b48Spatrick }
49109467b48Spatrick
lto_codegen_debug_options_array(lto_code_gen_t cg,const char * const * options,int number)49209467b48Spatrick void lto_codegen_debug_options_array(lto_code_gen_t cg,
49309467b48Spatrick const char *const *options, int number) {
49473471bf0Spatrick assert(optionParsingState != OptParsingState::Early &&
49573471bf0Spatrick "early option processing already happened");
496097a140dSpatrick SmallVector<StringRef, 4> Options;
497097a140dSpatrick for (int i = 0; i < number; ++i)
498097a140dSpatrick Options.push_back(options[i]);
499*d415bd75Srobert unwrap(cg)->setCodeGenDebugOptions(ArrayRef(Options));
50009467b48Spatrick }
50109467b48Spatrick
lto_api_version()50209467b48Spatrick unsigned int lto_api_version() { return LTO_API_VERSION; }
50309467b48Spatrick
lto_codegen_set_should_internalize(lto_code_gen_t cg,bool ShouldInternalize)50409467b48Spatrick void lto_codegen_set_should_internalize(lto_code_gen_t cg,
50509467b48Spatrick bool ShouldInternalize) {
50609467b48Spatrick unwrap(cg)->setShouldInternalize(ShouldInternalize);
50709467b48Spatrick }
50809467b48Spatrick
lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,lto_bool_t ShouldEmbedUselists)50909467b48Spatrick void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
51009467b48Spatrick lto_bool_t ShouldEmbedUselists) {
51109467b48Spatrick unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);
51209467b48Spatrick }
51309467b48Spatrick
lto_module_has_ctor_dtor(lto_module_t mod)514*d415bd75Srobert lto_bool_t lto_module_has_ctor_dtor(lto_module_t mod) {
515*d415bd75Srobert return unwrap(mod)->hasCtorDtor();
516*d415bd75Srobert }
517*d415bd75Srobert
51809467b48Spatrick // ThinLTO API below
51909467b48Spatrick
thinlto_create_codegen(void)52009467b48Spatrick thinlto_code_gen_t thinlto_create_codegen(void) {
52109467b48Spatrick lto_initialize();
52209467b48Spatrick ThinLTOCodeGenerator *CodeGen = new ThinLTOCodeGenerator();
52373471bf0Spatrick CodeGen->setTargetOptions(
52473471bf0Spatrick codegen::InitTargetOptionsFromCodeGenFlags(Triple()));
52509467b48Spatrick CodeGen->setFreestanding(EnableFreestanding);
52609467b48Spatrick
52709467b48Spatrick if (OptLevel.getNumOccurrences()) {
52809467b48Spatrick if (OptLevel < '0' || OptLevel > '3')
52909467b48Spatrick report_fatal_error("Optimization level must be between 0 and 3");
53009467b48Spatrick CodeGen->setOptLevel(OptLevel - '0');
531*d415bd75Srobert std::optional<CodeGenOpt::Level> CGOptLevelOrNone =
532*d415bd75Srobert CodeGenOpt::getLevel(OptLevel - '0');
533*d415bd75Srobert assert(CGOptLevelOrNone);
534*d415bd75Srobert CodeGen->setCodeGenOptLevel(*CGOptLevelOrNone);
53509467b48Spatrick }
53609467b48Spatrick return wrap(CodeGen);
53709467b48Spatrick }
53809467b48Spatrick
thinlto_codegen_dispose(thinlto_code_gen_t cg)53909467b48Spatrick void thinlto_codegen_dispose(thinlto_code_gen_t cg) { delete unwrap(cg); }
54009467b48Spatrick
thinlto_codegen_add_module(thinlto_code_gen_t cg,const char * Identifier,const char * Data,int Length)54109467b48Spatrick void thinlto_codegen_add_module(thinlto_code_gen_t cg, const char *Identifier,
54209467b48Spatrick const char *Data, int Length) {
54309467b48Spatrick unwrap(cg)->addModule(Identifier, StringRef(Data, Length));
54409467b48Spatrick }
54509467b48Spatrick
thinlto_codegen_process(thinlto_code_gen_t cg)54609467b48Spatrick void thinlto_codegen_process(thinlto_code_gen_t cg) { unwrap(cg)->run(); }
54709467b48Spatrick
thinlto_module_get_num_objects(thinlto_code_gen_t cg)54809467b48Spatrick unsigned int thinlto_module_get_num_objects(thinlto_code_gen_t cg) {
54909467b48Spatrick return unwrap(cg)->getProducedBinaries().size();
55009467b48Spatrick }
thinlto_module_get_object(thinlto_code_gen_t cg,unsigned int index)55109467b48Spatrick LTOObjectBuffer thinlto_module_get_object(thinlto_code_gen_t cg,
55209467b48Spatrick unsigned int index) {
55309467b48Spatrick assert(index < unwrap(cg)->getProducedBinaries().size() && "Index overflow");
55409467b48Spatrick auto &MemBuffer = unwrap(cg)->getProducedBinaries()[index];
55509467b48Spatrick return LTOObjectBuffer{MemBuffer->getBufferStart(),
55609467b48Spatrick MemBuffer->getBufferSize()};
55709467b48Spatrick }
55809467b48Spatrick
thinlto_module_get_num_object_files(thinlto_code_gen_t cg)55909467b48Spatrick unsigned int thinlto_module_get_num_object_files(thinlto_code_gen_t cg) {
56009467b48Spatrick return unwrap(cg)->getProducedBinaryFiles().size();
56109467b48Spatrick }
thinlto_module_get_object_file(thinlto_code_gen_t cg,unsigned int index)56209467b48Spatrick const char *thinlto_module_get_object_file(thinlto_code_gen_t cg,
56309467b48Spatrick unsigned int index) {
56409467b48Spatrick assert(index < unwrap(cg)->getProducedBinaryFiles().size() &&
56509467b48Spatrick "Index overflow");
56609467b48Spatrick return unwrap(cg)->getProducedBinaryFiles()[index].c_str();
56709467b48Spatrick }
56809467b48Spatrick
thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,lto_bool_t disable)56909467b48Spatrick void thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,
57009467b48Spatrick lto_bool_t disable) {
57109467b48Spatrick unwrap(cg)->disableCodeGen(disable);
57209467b48Spatrick }
57309467b48Spatrick
thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,lto_bool_t CodeGenOnly)57409467b48Spatrick void thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,
57509467b48Spatrick lto_bool_t CodeGenOnly) {
57609467b48Spatrick unwrap(cg)->setCodeGenOnly(CodeGenOnly);
57709467b48Spatrick }
57809467b48Spatrick
thinlto_debug_options(const char * const * options,int number)57909467b48Spatrick void thinlto_debug_options(const char *const *options, int number) {
58009467b48Spatrick // if options were requested, set them
58109467b48Spatrick if (number && options) {
58209467b48Spatrick std::vector<const char *> CodegenArgv(1, "libLTO");
58373471bf0Spatrick append_range(CodegenArgv, ArrayRef<const char *>(options, number));
58409467b48Spatrick cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
58509467b48Spatrick }
58609467b48Spatrick }
58709467b48Spatrick
lto_module_is_thinlto(lto_module_t mod)58809467b48Spatrick lto_bool_t lto_module_is_thinlto(lto_module_t mod) {
58909467b48Spatrick return unwrap(mod)->isThinLTO();
59009467b48Spatrick }
59109467b48Spatrick
thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,const char * Name,int Length)59209467b48Spatrick void thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,
59309467b48Spatrick const char *Name, int Length) {
59409467b48Spatrick unwrap(cg)->preserveSymbol(StringRef(Name, Length));
59509467b48Spatrick }
59609467b48Spatrick
thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,const char * Name,int Length)59709467b48Spatrick void thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,
59809467b48Spatrick const char *Name, int Length) {
59909467b48Spatrick unwrap(cg)->crossReferenceSymbol(StringRef(Name, Length));
60009467b48Spatrick }
60109467b48Spatrick
thinlto_codegen_set_cpu(thinlto_code_gen_t cg,const char * cpu)60209467b48Spatrick void thinlto_codegen_set_cpu(thinlto_code_gen_t cg, const char *cpu) {
60309467b48Spatrick return unwrap(cg)->setCpu(cpu);
60409467b48Spatrick }
60509467b48Spatrick
thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,const char * cache_dir)60609467b48Spatrick void thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,
60709467b48Spatrick const char *cache_dir) {
60809467b48Spatrick return unwrap(cg)->setCacheDir(cache_dir);
60909467b48Spatrick }
61009467b48Spatrick
thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,int interval)61109467b48Spatrick void thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,
61209467b48Spatrick int interval) {
61309467b48Spatrick return unwrap(cg)->setCachePruningInterval(interval);
61409467b48Spatrick }
61509467b48Spatrick
thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,unsigned expiration)61609467b48Spatrick void thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,
61709467b48Spatrick unsigned expiration) {
61809467b48Spatrick return unwrap(cg)->setCacheEntryExpiration(expiration);
61909467b48Spatrick }
62009467b48Spatrick
thinlto_codegen_set_final_cache_size_relative_to_available_space(thinlto_code_gen_t cg,unsigned Percentage)62109467b48Spatrick void thinlto_codegen_set_final_cache_size_relative_to_available_space(
62209467b48Spatrick thinlto_code_gen_t cg, unsigned Percentage) {
62309467b48Spatrick return unwrap(cg)->setMaxCacheSizeRelativeToAvailableSpace(Percentage);
62409467b48Spatrick }
62509467b48Spatrick
thinlto_codegen_set_cache_size_bytes(thinlto_code_gen_t cg,unsigned MaxSizeBytes)62609467b48Spatrick void thinlto_codegen_set_cache_size_bytes(
62709467b48Spatrick thinlto_code_gen_t cg, unsigned MaxSizeBytes) {
62809467b48Spatrick return unwrap(cg)->setCacheMaxSizeBytes(MaxSizeBytes);
62909467b48Spatrick }
63009467b48Spatrick
thinlto_codegen_set_cache_size_megabytes(thinlto_code_gen_t cg,unsigned MaxSizeMegabytes)63109467b48Spatrick void thinlto_codegen_set_cache_size_megabytes(
63209467b48Spatrick thinlto_code_gen_t cg, unsigned MaxSizeMegabytes) {
63309467b48Spatrick uint64_t MaxSizeBytes = MaxSizeMegabytes;
63409467b48Spatrick MaxSizeBytes *= 1024 * 1024;
63509467b48Spatrick return unwrap(cg)->setCacheMaxSizeBytes(MaxSizeBytes);
63609467b48Spatrick }
63709467b48Spatrick
thinlto_codegen_set_cache_size_files(thinlto_code_gen_t cg,unsigned MaxSizeFiles)63809467b48Spatrick void thinlto_codegen_set_cache_size_files(
63909467b48Spatrick thinlto_code_gen_t cg, unsigned MaxSizeFiles) {
64009467b48Spatrick return unwrap(cg)->setCacheMaxSizeFiles(MaxSizeFiles);
64109467b48Spatrick }
64209467b48Spatrick
thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,const char * save_temps_dir)64309467b48Spatrick void thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,
64409467b48Spatrick const char *save_temps_dir) {
64509467b48Spatrick return unwrap(cg)->setSaveTempsDir(save_temps_dir);
64609467b48Spatrick }
64709467b48Spatrick
thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,const char * save_temps_dir)64809467b48Spatrick void thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,
64909467b48Spatrick const char *save_temps_dir) {
65009467b48Spatrick unwrap(cg)->setGeneratedObjectsDirectory(save_temps_dir);
65109467b48Spatrick }
65209467b48Spatrick
thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,lto_codegen_model model)65309467b48Spatrick lto_bool_t thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,
65409467b48Spatrick lto_codegen_model model) {
65509467b48Spatrick switch (model) {
65609467b48Spatrick case LTO_CODEGEN_PIC_MODEL_STATIC:
65709467b48Spatrick unwrap(cg)->setCodePICModel(Reloc::Static);
65809467b48Spatrick return false;
65909467b48Spatrick case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
66009467b48Spatrick unwrap(cg)->setCodePICModel(Reloc::PIC_);
66109467b48Spatrick return false;
66209467b48Spatrick case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
66309467b48Spatrick unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
66409467b48Spatrick return false;
66509467b48Spatrick case LTO_CODEGEN_PIC_MODEL_DEFAULT:
666*d415bd75Srobert unwrap(cg)->setCodePICModel(std::nullopt);
66709467b48Spatrick return false;
66809467b48Spatrick }
66909467b48Spatrick sLastErrorString = "Unknown PIC model";
67009467b48Spatrick return true;
67109467b48Spatrick }
67209467b48Spatrick
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(lto::InputFile,lto_input_t)67309467b48Spatrick DEFINE_SIMPLE_CONVERSION_FUNCTIONS(lto::InputFile, lto_input_t)
67409467b48Spatrick
67509467b48Spatrick lto_input_t lto_input_create(const void *buffer, size_t buffer_size, const char *path) {
67609467b48Spatrick return wrap(LTOModule::createInputFile(buffer, buffer_size, path, sLastErrorString));
67709467b48Spatrick }
67809467b48Spatrick
lto_input_dispose(lto_input_t input)67909467b48Spatrick void lto_input_dispose(lto_input_t input) {
68009467b48Spatrick delete unwrap(input);
68109467b48Spatrick }
68209467b48Spatrick
lto_input_get_num_dependent_libraries(lto_input_t input)68309467b48Spatrick extern unsigned lto_input_get_num_dependent_libraries(lto_input_t input) {
68409467b48Spatrick return LTOModule::getDependentLibraryCount(unwrap(input));
68509467b48Spatrick }
68609467b48Spatrick
lto_input_get_dependent_library(lto_input_t input,size_t index,size_t * size)68709467b48Spatrick extern const char *lto_input_get_dependent_library(lto_input_t input,
68809467b48Spatrick size_t index,
68909467b48Spatrick size_t *size) {
69009467b48Spatrick return LTOModule::getDependentLibrary(unwrap(input), index, size);
69109467b48Spatrick }
69209467b48Spatrick
lto_runtime_lib_symbols_list(size_t * size)69309467b48Spatrick extern const char *const *lto_runtime_lib_symbols_list(size_t *size) {
69409467b48Spatrick auto symbols = lto::LTO::getRuntimeLibcallSymbols();
69509467b48Spatrick *size = symbols.size();
69609467b48Spatrick return symbols.data();
69709467b48Spatrick }
698