1//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Link Time Optimization library. This library is
10// intended to be used by linker to optimize code at link time.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-c/lto.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Bitcode/BitcodeReader.h"
19#include "llvm/CodeGen/CommandFlags.h"
20#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/LTO/LTO.h"
24#include "llvm/LTO/legacy/LTOCodeGenerator.h"
25#include "llvm/LTO/legacy/LTOModule.h"
26#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/Signals.h"
30#include "llvm/Support/TargetSelect.h"
31#include "llvm/Support/raw_ostream.h"
32
33using namespace llvm;
34
35static codegen::RegisterCodeGenFlags CGF;
36
37// extra command-line flags needed for LTOCodeGenerator
38static cl::opt<char>
39 OptLevel("O",
40 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
41 "(default = '-O2')"),
42 cl::Prefix, cl::init(Val: '2'));
43
44static cl::opt<bool> EnableFreestanding(
45 "lto-freestanding", cl::init(Val: false),
46 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
47
48static cl::opt<std::string> ThinLTOCacheDir(
49 "legacy-thinlto-cache-dir",
50 cl::desc("Experimental option, enable ThinLTO caching. Note: the cache "
51 "currently does not take the mcmodel setting into account, so you "
52 "might get false hits if different mcmodels are used in different "
53 "builds using the same cache directory."));
54
55static cl::opt<int> ThinLTOCachePruningInterval(
56 "legacy-thinlto-cache-pruning-interval", cl::init(Val: 1200),
57 cl::desc("Set ThinLTO cache pruning interval (seconds)."));
58
59static cl::opt<uint64_t> ThinLTOCacheMaxSizeBytes(
60 "legacy-thinlto-cache-max-size-bytes",
61 cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."));
62
63static cl::opt<int> ThinLTOCacheMaxSizeFiles(
64 "legacy-thinlto-cache-max-size-files", cl::init(Val: 1000000),
65 cl::desc("Set ThinLTO cache pruning directory maximum number of files."));
66
67static cl::opt<unsigned> ThinLTOCacheEntryExpiration(
68 "legacy-thinlto-cache-entry-expiration", cl::init(Val: 604800) /* 1w */,
69 cl::desc("Set ThinLTO cache entry expiration time (seconds)."));
70
71#ifdef NDEBUG
72static bool VerifyByDefault = false;
73#else
74static bool VerifyByDefault = true;
75#endif
76
77static cl::opt<bool> DisableVerify(
78 "disable-llvm-verifier", cl::init(Val: !VerifyByDefault),
79 cl::desc("Don't run the LLVM verifier during the optimization pipeline"));
80
81// Holds most recent error string.
82// *** Not thread safe ***
83static std::string sLastErrorString;
84
85// Holds the initialization state of the LTO module.
86// *** Not thread safe ***
87static bool initialized = false;
88
89// Represent the state of parsing command line debug options.
90static enum class OptParsingState {
91 NotParsed, // Initial state.
92 Early, // After lto_set_debug_options is called.
93 Done // After maybeParseOptions is called.
94} optionParsingState = OptParsingState::NotParsed;
95
96static LLVMContext *LTOContext = nullptr;
97
98// Records -mllvm arguments parsed through the legacy debug-option APIs.
99static std::vector<std::string> ThinLTOMllvmArgs;
100
101struct LTOToolDiagnosticHandler : public DiagnosticHandler {
102 bool handleDiagnostics(const DiagnosticInfo &DI) override {
103 if (DI.getSeverity() != DS_Error) {
104 DiagnosticPrinterRawOStream DP(errs());
105 DI.print(DP);
106 errs() << '\n';
107 return true;
108 }
109 sLastErrorString = "";
110 {
111 raw_string_ostream Stream(sLastErrorString);
112 DiagnosticPrinterRawOStream DP(Stream);
113 DI.print(DP);
114 }
115 return true;
116 }
117};
118
119static SmallVector<const char *> RuntimeLibcallSymbols;
120
121// Initialize the configured targets if they have not been initialized.
122static void lto_initialize() {
123 if (!initialized) {
124#ifdef _WIN32
125 // Dialog box on crash disabling doesn't work across DLL boundaries, so do
126 // it here.
127 llvm::sys::DisableSystemDialogsOnCrash();
128#endif
129
130 InitializeAllTargetInfos();
131 InitializeAllTargets();
132 InitializeAllTargetMCs();
133 InitializeAllAsmParsers();
134 InitializeAllAsmPrinters();
135 InitializeAllDisassemblers();
136
137 static LLVMContext Context;
138 LTOContext = &Context;
139 LTOContext->setDiagnosticHandler(
140 DH: std::make_unique<LTOToolDiagnosticHandler>(), RespectFilters: true);
141 RuntimeLibcallSymbols = lto::LTO::getRuntimeLibcallSymbols(TT: Triple());
142 initialized = true;
143 }
144}
145
146namespace {
147
148static void handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,
149 const char *Msg, void *) {
150 sLastErrorString = Msg;
151}
152
153// This derived class owns the native object file. This helps implement the
154// libLTO API semantics, which require that the code generator owns the object
155// file.
156struct LibLTOCodeGenerator : LTOCodeGenerator {
157 LibLTOCodeGenerator() : LTOCodeGenerator(*LTOContext) { init(); }
158 LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
159 : LTOCodeGenerator(*Context), OwnedContext(std::move(Context)) {
160 init();
161 }
162
163 // Reset the module first in case MergedModule is created in OwnedContext.
164 // Module must be destructed before its context gets destructed.
165 ~LibLTOCodeGenerator() { resetMergedModule(); }
166
167 void init() { setDiagnosticHandler(handleLibLTODiagnostic, nullptr); }
168
169 std::unique_ptr<MemoryBuffer> NativeObjectFile;
170 std::unique_ptr<LLVMContext> OwnedContext;
171};
172
173}
174
175DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
176DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThinLTOCodeGenerator, thinlto_code_gen_t)
177DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
178
179// Convert the subtarget features into a string to pass to LTOCodeGenerator.
180static void lto_add_attrs(lto_code_gen_t cg) {
181 LTOCodeGenerator *CG = unwrap(P: cg);
182 CG->setAttrs(codegen::getMAttrs());
183
184 if (OptLevel < '0' || OptLevel > '3')
185 report_fatal_error(reason: "Optimization level must be between 0 and 3");
186 CG->setOptLevel(OptLevel - '0');
187 CG->setFreestanding(EnableFreestanding);
188 CG->setDisableVerify(DisableVerify);
189}
190
191extern const char* lto_get_version() {
192 return LTOCodeGenerator::getVersionString();
193}
194
195const char* lto_get_error_message() {
196 return sLastErrorString.c_str();
197}
198
199bool lto_module_is_object_file(const char* path) {
200 return LTOModule::isBitcodeFile(path: StringRef(path));
201}
202
203bool lto_module_is_object_file_for_target(const char* path,
204 const char* target_triplet_prefix) {
205 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(Filename: path);
206 if (!Buffer)
207 return false;
208 return LTOModule::isBitcodeForTarget(memBuffer: Buffer->get(),
209 triplePrefix: StringRef(target_triplet_prefix));
210}
211
212bool lto_module_has_objc_category(const void *mem, size_t length) {
213 std::unique_ptr<MemoryBuffer> Buffer(LTOModule::makeBuffer(mem, length));
214 if (!Buffer)
215 return false;
216 LLVMContext Ctx;
217 ErrorOr<bool> Result = expectedToErrorOrAndEmitErrors(
218 Ctx, Val: llvm::isBitcodeContainingObjCCategory(Buffer: *Buffer));
219 return Result && *Result;
220}
221
222bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
223 return LTOModule::isBitcodeFile(mem, length);
224}
225
226bool
227lto_module_is_object_file_in_memory_for_target(const void* mem,
228 size_t length,
229 const char* target_triplet_prefix) {
230 std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
231 if (!buffer)
232 return false;
233 return LTOModule::isBitcodeForTarget(memBuffer: buffer.get(),
234 triplePrefix: StringRef(target_triplet_prefix));
235}
236
237lto_module_t lto_module_create(const char* path) {
238 lto_initialize();
239 llvm::TargetOptions Options =
240 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
241 ErrorOr<std::unique_ptr<LTOModule>> M =
242 LTOModule::createFromFile(Context&: *LTOContext, path: StringRef(path), options: Options);
243 if (!M)
244 return nullptr;
245 return wrap(P: M->release());
246}
247
248lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
249 lto_initialize();
250 llvm::TargetOptions Options =
251 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
252 ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFile(
253 Context&: *LTOContext, fd, path: StringRef(path), size, options: Options);
254 if (!M)
255 return nullptr;
256 return wrap(P: M->release());
257}
258
259lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
260 size_t file_size,
261 size_t map_size,
262 off_t offset) {
263 lto_initialize();
264 llvm::TargetOptions Options =
265 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
266 ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFileSlice(
267 Context&: *LTOContext, fd, path: StringRef(path), map_size, offset, options: Options);
268 if (!M)
269 return nullptr;
270 return wrap(P: M->release());
271}
272
273lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
274 lto_initialize();
275 llvm::TargetOptions Options =
276 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
277 ErrorOr<std::unique_ptr<LTOModule>> M =
278 LTOModule::createFromBuffer(Context&: *LTOContext, mem, length, options: Options);
279 if (!M)
280 return nullptr;
281 return wrap(P: M->release());
282}
283
284lto_module_t lto_module_create_from_memory_with_path(const void* mem,
285 size_t length,
286 const char *path) {
287 lto_initialize();
288 llvm::TargetOptions Options =
289 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
290 ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
291 Context&: *LTOContext, mem, length, options: Options, path: StringRef(path));
292 if (!M)
293 return nullptr;
294 return wrap(P: M->release());
295}
296
297lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
298 const char *path) {
299 lto_initialize();
300 llvm::TargetOptions Options =
301 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
302
303 // Create a local context. Ownership will be transferred to LTOModule.
304 std::unique_ptr<LLVMContext> Context = std::make_unique<LLVMContext>();
305 Context->setDiagnosticHandler(DH: std::make_unique<LTOToolDiagnosticHandler>(),
306 RespectFilters: true);
307
308 ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createInLocalContext(
309 Context: std::move(Context), mem, length, options: Options, path: StringRef(path));
310 if (!M)
311 return nullptr;
312 return wrap(P: M->release());
313}
314
315lto_module_t lto_module_create_in_codegen_context(const void *mem,
316 size_t length,
317 const char *path,
318 lto_code_gen_t cg) {
319 lto_initialize();
320 llvm::TargetOptions Options =
321 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
322 ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
323 Context&: unwrap(P: cg)->getContext(), mem, length, options: Options, path: StringRef(path));
324 if (!M)
325 return nullptr;
326 return wrap(P: M->release());
327}
328
329void lto_module_dispose(lto_module_t mod) { delete unwrap(P: mod); }
330
331const char* lto_module_get_target_triple(lto_module_t mod) {
332 return unwrap(P: mod)->getTargetTriple().str().c_str();
333}
334
335void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
336 return unwrap(P: mod)->setTargetTriple(Triple(StringRef(triple)));
337}
338
339unsigned int lto_module_get_num_symbols(lto_module_t mod) {
340 return unwrap(P: mod)->getSymbolCount();
341}
342
343const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
344 return unwrap(P: mod)->getSymbolName(index).data();
345}
346
347lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
348 unsigned int index) {
349 return unwrap(P: mod)->getSymbolAttributes(index);
350}
351
352unsigned int lto_module_get_num_asm_undef_symbols(lto_module_t mod) {
353 return unwrap(P: mod)->getAsmUndefSymbolCount();
354}
355
356const char *lto_module_get_asm_undef_symbol_name(lto_module_t mod,
357 unsigned int index) {
358 return unwrap(P: mod)->getAsmUndefSymbolName(index).data();
359}
360
361const char* lto_module_get_linkeropts(lto_module_t mod) {
362 return unwrap(P: mod)->getLinkerOpts().data();
363}
364
365lto_bool_t lto_module_get_macho_cputype(lto_module_t mod,
366 unsigned int *out_cputype,
367 unsigned int *out_cpusubtype) {
368 LTOModule *M = unwrap(P: mod);
369 Expected<uint32_t> CPUType = M->getMachOCPUType();
370 if (!CPUType) {
371 sLastErrorString = toString(E: CPUType.takeError());
372 return true;
373 }
374 *out_cputype = *CPUType;
375
376 Expected<uint32_t> CPUSubType = M->getMachOCPUSubType();
377 if (!CPUSubType) {
378 sLastErrorString = toString(E: CPUSubType.takeError());
379 return true;
380 }
381 *out_cpusubtype = *CPUSubType;
382
383 return false;
384}
385
386void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
387 lto_diagnostic_handler_t diag_handler,
388 void *ctxt) {
389 unwrap(P: cg)->setDiagnosticHandler(diag_handler, ctxt);
390}
391
392static lto_code_gen_t createCodeGen(bool InLocalContext) {
393 lto_initialize();
394
395 TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
396
397 LibLTOCodeGenerator *CodeGen =
398 InLocalContext ? new LibLTOCodeGenerator(std::make_unique<LLVMContext>())
399 : new LibLTOCodeGenerator();
400 CodeGen->setTargetOptions(Options);
401 return wrap(P: CodeGen);
402}
403
404lto_code_gen_t lto_codegen_create(void) {
405 return createCodeGen(/* InLocalContext */ false);
406}
407
408lto_code_gen_t lto_codegen_create_in_local_context(void) {
409 return createCodeGen(/* InLocalContext */ true);
410}
411
412void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(P: cg); }
413
414bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
415 return !unwrap(P: cg)->addModule(unwrap(P: mod));
416}
417
418void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
419 unwrap(P: cg)->setModule(std::unique_ptr<LTOModule>(unwrap(P: mod)));
420}
421
422bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
423 unwrap(P: cg)->setDebugInfo(debug);
424 return false;
425}
426
427bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
428 switch (model) {
429 case LTO_CODEGEN_PIC_MODEL_STATIC:
430 unwrap(P: cg)->setCodePICModel(Reloc::Static);
431 return false;
432 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
433 unwrap(P: cg)->setCodePICModel(Reloc::PIC_);
434 return false;
435 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
436 unwrap(P: cg)->setCodePICModel(Reloc::DynamicNoPIC);
437 return false;
438 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
439 unwrap(P: cg)->setCodePICModel(std::nullopt);
440 return false;
441 }
442 sLastErrorString = "Unknown PIC model";
443 return true;
444}
445
446void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
447 return unwrap(P: cg)->setCpu(cpu);
448}
449
450void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
451 // In here only for backwards compatibility. We use MC now.
452}
453
454void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
455 int nargs) {
456 // In here only for backwards compatibility. We use MC now.
457}
458
459void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
460 const char *symbol) {
461 unwrap(P: cg)->addMustPreserveSymbol(Sym: symbol);
462}
463
464static void maybeParseOptions(lto_code_gen_t cg) {
465 if (optionParsingState != OptParsingState::Done) {
466 // Parse options if any were set by the lto_codegen_debug_options* function.
467 unwrap(P: cg)->parseCodeGenDebugOptions();
468 lto_add_attrs(cg);
469 optionParsingState = OptParsingState::Done;
470 }
471}
472
473bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
474 maybeParseOptions(cg);
475 return !unwrap(P: cg)->writeMergedModules(Path: path);
476}
477
478const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
479 maybeParseOptions(cg);
480 LibLTOCodeGenerator *CG = unwrap(P: cg);
481 CG->NativeObjectFile = CG->compile();
482 if (!CG->NativeObjectFile)
483 return nullptr;
484 *length = CG->NativeObjectFile->getBufferSize();
485 return CG->NativeObjectFile->getBufferStart();
486}
487
488bool lto_codegen_optimize(lto_code_gen_t cg) {
489 maybeParseOptions(cg);
490 return !unwrap(P: cg)->optimize();
491}
492
493const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
494 maybeParseOptions(cg);
495 LibLTOCodeGenerator *CG = unwrap(P: cg);
496 CG->NativeObjectFile = CG->compileOptimized();
497 if (!CG->NativeObjectFile)
498 return nullptr;
499 *length = CG->NativeObjectFile->getBufferSize();
500 return CG->NativeObjectFile->getBufferStart();
501}
502
503bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
504 maybeParseOptions(cg);
505 return !unwrap(P: cg)->compile_to_file(Name: name);
506}
507
508void lto_set_debug_options(const char *const *options, int number) {
509 assert(optionParsingState == OptParsingState::NotParsed &&
510 "option processing already happened");
511 // Need to put each suboption in a null-terminated string before passing to
512 // parseCommandLineOptions().
513 std::vector<std::string> Options;
514 llvm::append_range(C&: Options, R: ArrayRef(options, number));
515
516 llvm::parseCommandLineOptions(Options);
517 optionParsingState = OptParsingState::Early;
518}
519
520void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
521 assert(optionParsingState != OptParsingState::Early &&
522 "early option processing already happened");
523 SmallVector<StringRef, 4> Options;
524 for (std::pair<StringRef, StringRef> o = getToken(Source: opt); !o.first.empty();
525 o = getToken(Source: o.second))
526 Options.push_back(Elt: o.first);
527
528 unwrap(P: cg)->setCodeGenDebugOptions(Options);
529}
530
531void lto_codegen_debug_options_array(lto_code_gen_t cg,
532 const char *const *options, int number) {
533 assert(optionParsingState != OptParsingState::Early &&
534 "early option processing already happened");
535 SmallVector<StringRef, 4> Options(ArrayRef(options, number));
536 unwrap(P: cg)->setCodeGenDebugOptions(ArrayRef(Options));
537}
538
539unsigned int lto_api_version() { return LTO_API_VERSION; }
540
541void lto_codegen_set_should_internalize(lto_code_gen_t cg,
542 bool ShouldInternalize) {
543 unwrap(P: cg)->setShouldInternalize(ShouldInternalize);
544}
545
546void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
547 lto_bool_t ShouldEmbedUselists) {
548 unwrap(P: cg)->setShouldEmbedUselists(ShouldEmbedUselists);
549}
550
551lto_bool_t lto_module_has_ctor_dtor(lto_module_t mod) {
552 return unwrap(P: mod)->hasCtorDtor();
553}
554
555// ThinLTO API below
556
557thinlto_code_gen_t thinlto_create_codegen(void) {
558 lto_initialize();
559 ThinLTOCodeGenerator *CodeGen = new ThinLTOCodeGenerator();
560 CodeGen->setMllvmArgs(ThinLTOMllvmArgs);
561 CodeGen->setTargetOptions(
562 codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple()));
563 CodeGen->setFreestanding(EnableFreestanding);
564
565 if (OptLevel.getNumOccurrences()) {
566 if (OptLevel < '0' || OptLevel > '3')
567 report_fatal_error(reason: "Optimization level must be between 0 and 3");
568 CodeGen->setOptLevel(OptLevel - '0');
569 std::optional<CodeGenOptLevel> CGOptLevelOrNone =
570 CodeGenOpt::getLevel(OL: OptLevel - '0');
571 assert(CGOptLevelOrNone);
572 CodeGen->setCodeGenOptLevel(*CGOptLevelOrNone);
573 }
574 if (!ThinLTOCacheDir.empty()) {
575 auto Err = llvm::sys::fs::create_directories(path: ThinLTOCacheDir);
576 if (Err)
577 report_fatal_error(reason: Twine("Unable to create thinLTO cache directory: ") +
578 Err.message());
579 bool result;
580 Err = llvm::sys::fs::is_directory(path: ThinLTOCacheDir, result);
581 if (Err || !result)
582 report_fatal_error(reason: Twine("Unable to get status of thinLTO cache path or "
583 "path is not a directory: ") +
584 Err.message());
585 CodeGen->setCacheDir(ThinLTOCacheDir);
586
587 CodeGen->setCachePruningInterval(ThinLTOCachePruningInterval);
588 CodeGen->setCacheEntryExpiration(ThinLTOCacheEntryExpiration);
589 CodeGen->setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
590 CodeGen->setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
591 }
592
593 return wrap(P: CodeGen);
594}
595
596void thinlto_codegen_dispose(thinlto_code_gen_t cg) { delete unwrap(P: cg); }
597
598void thinlto_codegen_add_module(thinlto_code_gen_t cg, const char *Identifier,
599 const char *Data, int Length) {
600 unwrap(P: cg)->addModule(Identifier, Data: StringRef(Data, Length));
601}
602
603void thinlto_codegen_process(thinlto_code_gen_t cg) { unwrap(P: cg)->run(); }
604
605unsigned int thinlto_module_get_num_objects(thinlto_code_gen_t cg) {
606 return unwrap(P: cg)->getProducedBinaries().size();
607}
608LTOObjectBuffer thinlto_module_get_object(thinlto_code_gen_t cg,
609 unsigned int index) {
610 assert(index < unwrap(cg)->getProducedBinaries().size() && "Index overflow");
611 auto &MemBuffer = unwrap(P: cg)->getProducedBinaries()[index];
612 return LTOObjectBuffer{.Buffer: MemBuffer->getBufferStart(),
613 .Size: MemBuffer->getBufferSize()};
614}
615
616unsigned int thinlto_module_get_num_object_files(thinlto_code_gen_t cg) {
617 return unwrap(P: cg)->getProducedBinaryFiles().size();
618}
619const char *thinlto_module_get_object_file(thinlto_code_gen_t cg,
620 unsigned int index) {
621 assert(index < unwrap(cg)->getProducedBinaryFiles().size() &&
622 "Index overflow");
623 return unwrap(P: cg)->getProducedBinaryFiles()[index].c_str();
624}
625
626void thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,
627 lto_bool_t disable) {
628 unwrap(P: cg)->disableCodeGen(Disable: disable);
629}
630
631void thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,
632 lto_bool_t CodeGenOnly) {
633 unwrap(P: cg)->setCodeGenOnly(CodeGenOnly);
634}
635
636void thinlto_debug_options(const char *const *options, int number) {
637 // If options were requested, parse and retain them.
638 if (number && options) {
639 std::vector<const char *> CodegenArgv(1, "libLTO");
640 append_range(C&: CodegenArgv, R: ArrayRef<const char *>(options, number));
641 cl::ParseCommandLineOptions(argc: CodegenArgv.size(), argv: CodegenArgv.data());
642 ThinLTOMllvmArgs.assign(first: options, last: options + number);
643 }
644}
645
646lto_bool_t lto_module_is_thinlto(lto_module_t mod) {
647 return unwrap(P: mod)->isThinLTO();
648}
649
650void thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,
651 const char *Name, int Length) {
652 unwrap(P: cg)->preserveSymbol(Name: StringRef(Name, Length));
653}
654
655void thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,
656 const char *Name, int Length) {
657 unwrap(P: cg)->crossReferenceSymbol(Name: StringRef(Name, Length));
658}
659
660void thinlto_codegen_set_cpu(thinlto_code_gen_t cg, const char *cpu) {
661 return unwrap(P: cg)->setCpu(cpu);
662}
663
664void thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,
665 const char *cache_dir) {
666 return unwrap(P: cg)->setCacheDir(cache_dir);
667}
668
669void thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,
670 int interval) {
671 return unwrap(P: cg)->setCachePruningInterval(interval);
672}
673
674void thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,
675 unsigned expiration) {
676 return unwrap(P: cg)->setCacheEntryExpiration(expiration);
677}
678
679void thinlto_codegen_set_final_cache_size_relative_to_available_space(
680 thinlto_code_gen_t cg, unsigned Percentage) {
681 return unwrap(P: cg)->setMaxCacheSizeRelativeToAvailableSpace(Percentage);
682}
683
684void thinlto_codegen_set_cache_size_bytes(
685 thinlto_code_gen_t cg, unsigned MaxSizeBytes) {
686 return unwrap(P: cg)->setCacheMaxSizeBytes(MaxSizeBytes);
687}
688
689void thinlto_codegen_set_cache_size_megabytes(
690 thinlto_code_gen_t cg, unsigned MaxSizeMegabytes) {
691 uint64_t MaxSizeBytes = MaxSizeMegabytes;
692 MaxSizeBytes *= 1024 * 1024;
693 return unwrap(P: cg)->setCacheMaxSizeBytes(MaxSizeBytes);
694}
695
696void thinlto_codegen_set_cache_size_files(
697 thinlto_code_gen_t cg, unsigned MaxSizeFiles) {
698 return unwrap(P: cg)->setCacheMaxSizeFiles(MaxSizeFiles);
699}
700
701void thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,
702 const char *save_temps_dir) {
703 return unwrap(P: cg)->setSaveTempsDir(save_temps_dir);
704}
705
706void thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,
707 const char *save_temps_dir) {
708 unwrap(P: cg)->setGeneratedObjectsDirectory(save_temps_dir);
709}
710
711lto_bool_t thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,
712 lto_codegen_model model) {
713 switch (model) {
714 case LTO_CODEGEN_PIC_MODEL_STATIC:
715 unwrap(P: cg)->setCodePICModel(Reloc::Static);
716 return false;
717 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
718 unwrap(P: cg)->setCodePICModel(Reloc::PIC_);
719 return false;
720 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
721 unwrap(P: cg)->setCodePICModel(Reloc::DynamicNoPIC);
722 return false;
723 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
724 unwrap(P: cg)->setCodePICModel(std::nullopt);
725 return false;
726 }
727 sLastErrorString = "Unknown PIC model";
728 return true;
729}
730
731DEFINE_SIMPLE_CONVERSION_FUNCTIONS(lto::InputFile, lto_input_t)
732
733lto_input_t lto_input_create(const void *buffer, size_t buffer_size, const char *path) {
734 return wrap(P: LTOModule::createInputFile(buffer, buffer_size, path, out_error&: sLastErrorString));
735}
736
737void lto_input_dispose(lto_input_t input) {
738 delete unwrap(P: input);
739}
740
741extern unsigned lto_input_get_num_dependent_libraries(lto_input_t input) {
742 return LTOModule::getDependentLibraryCount(input: unwrap(P: input));
743}
744
745extern const char *lto_input_get_dependent_library(lto_input_t input,
746 size_t index,
747 size_t *size) {
748 return LTOModule::getDependentLibrary(input: unwrap(P: input), index, size);
749}
750
751extern const char *const *lto_runtime_lib_symbols_list(size_t *size) {
752 *size = RuntimeLibcallSymbols.size();
753 return RuntimeLibcallSymbols.data();
754}
755