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/LibraryOptionsContext.h"
29#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/Signals.h"
31#include "llvm/Support/TargetSelect.h"
32#include "llvm/Support/raw_ostream.h"
33
34using namespace llvm;
35
36// extra command-line flags needed for LTOCodeGenerator
37static cl::opt<char>
38 OptLevel("O",
39 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
40 "(default = '-O2')"),
41 cl::Prefix, cl::init(Val: '2'));
42
43static cl::opt<bool> EnableFreestanding(
44 "lto-freestanding", cl::init(Val: false),
45 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
46
47static cl::opt<std::string> ThinLTOCacheDir(
48 "legacy-thinlto-cache-dir",
49 cl::desc("Experimental option, enable ThinLTO caching. Note: the cache "
50 "currently does not take the mcmodel setting into account, so you "
51 "might get false hits if different mcmodels are used in different "
52 "builds using the same cache directory."));
53
54static cl::opt<int> ThinLTOCachePruningInterval(
55 "legacy-thinlto-cache-pruning-interval", cl::init(Val: 1200),
56 cl::desc("Set ThinLTO cache pruning interval (seconds)."));
57
58static cl::opt<uint64_t> ThinLTOCacheMaxSizeBytes(
59 "legacy-thinlto-cache-max-size-bytes",
60 cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."));
61
62static cl::opt<int> ThinLTOCacheMaxSizeFiles(
63 "legacy-thinlto-cache-max-size-files", cl::init(Val: 1000000),
64 cl::desc("Set ThinLTO cache pruning directory maximum number of files."));
65
66static cl::opt<unsigned> ThinLTOCacheEntryExpiration(
67 "legacy-thinlto-cache-entry-expiration", cl::init(Val: 604800) /* 1w */,
68 cl::desc("Set ThinLTO cache entry expiration time (seconds)."));
69
70#ifdef NDEBUG
71static bool VerifyByDefault = false;
72#else
73static bool VerifyByDefault = true;
74#endif
75
76static cl::opt<bool> DisableVerify(
77 "disable-llvm-verifier", cl::init(Val: !VerifyByDefault),
78 cl::desc("Don't run the LLVM verifier during the optimization pipeline"));
79
80// Holds most recent error string.
81// *** Not thread safe ***
82static std::string sLastErrorString;
83
84// Holds the initialization state of the LTO module.
85// *** Not thread safe ***
86static bool initialized = false;
87
88// Represent the state of parsing command line debug options.
89static enum class OptParsingState {
90 NotParsed, // Initial state.
91 Early, // After lto_set_debug_options is called.
92 Done // After maybeParseOptions is called.
93} optionParsingState = OptParsingState::NotParsed;
94
95static LLVMContext *LTOContext = nullptr;
96
97// Records -mllvm arguments parsed through the legacy debug-option APIs.
98static std::vector<std::string> ThinLTOMllvmArgs;
99
100struct LTOToolDiagnosticHandler : public DiagnosticHandler {
101 bool handleDiagnostics(const DiagnosticInfo &DI) override {
102 if (DI.getSeverity() != DS_Error) {
103 DiagnosticPrinterRawOStream DP(errs());
104 DI.print(DP);
105 errs() << '\n';
106 return true;
107 }
108 sLastErrorString = "";
109 {
110 raw_string_ostream Stream(sLastErrorString);
111 DiagnosticPrinterRawOStream DP(Stream);
112 DI.print(DP);
113 }
114 return true;
115 }
116};
117
118static SmallVector<const char *> RuntimeLibcallSymbols;
119
120// Initialize the configured targets if they have not been initialized.
121static void lto_initialize() {
122 if (!initialized) {
123#ifdef _WIN32
124 // Dialog box on crash disabling doesn't work across DLL boundaries, so do
125 // it here.
126 llvm::sys::DisableSystemDialogsOnCrash();
127#endif
128
129 InitializeAllTargetInfos();
130 InitializeAllTargets();
131 InitializeAllTargetMCs();
132 InitializeAllAsmParsers();
133 InitializeAllAsmPrinters();
134 InitializeAllDisassemblers();
135
136 static LLVMContext Context;
137 LTOContext = &Context;
138 LTOContext->setDiagnosticHandler(
139 DH: std::make_unique<LTOToolDiagnosticHandler>(), RespectFilters: true);
140 RuntimeLibcallSymbols = lto::LTO::getRuntimeLibcallSymbols(TT: Triple());
141 initialized = true;
142 }
143}
144
145namespace {
146
147static void handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,
148 const char *Msg, void *) {
149 sLastErrorString = Msg;
150}
151
152// This derived class owns the native object file. This helps implement the
153// libLTO API semantics, which require that the code generator owns the object
154// file.
155struct LibLTOCodeGenerator : LTOCodeGenerator {
156 LibLTOCodeGenerator() : LTOCodeGenerator(*LTOContext) { init(); }
157 LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
158 : LTOCodeGenerator(*Context), OwnedContext(std::move(Context)) {
159 OwnedContext->getLibraryOptions().assign(Other: LTOContext->getLibraryOptions());
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(C: LTOContext->getLibraryOptions()));
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::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), 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::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), 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::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), 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::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), 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::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), 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::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), 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::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), 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 =
396 codegen::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), TheTriple: Triple());
397
398 LibLTOCodeGenerator *CodeGen =
399 InLocalContext ? new LibLTOCodeGenerator(std::make_unique<LLVMContext>())
400 : new LibLTOCodeGenerator();
401 CodeGen->setTargetOptions(Options);
402 return wrap(P: CodeGen);
403}
404
405lto_code_gen_t lto_codegen_create(void) {
406 return createCodeGen(/* InLocalContext */ false);
407}
408
409lto_code_gen_t lto_codegen_create_in_local_context(void) {
410 return createCodeGen(/* InLocalContext */ true);
411}
412
413void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(P: cg); }
414
415bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
416 return !unwrap(P: cg)->addModule(unwrap(P: mod));
417}
418
419void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
420 unwrap(P: cg)->setModule(std::unique_ptr<LTOModule>(unwrap(P: mod)));
421}
422
423bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
424 unwrap(P: cg)->setDebugInfo(debug);
425 return false;
426}
427
428bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
429 switch (model) {
430 case LTO_CODEGEN_PIC_MODEL_STATIC:
431 unwrap(P: cg)->setCodePICModel(Reloc::Static);
432 return false;
433 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
434 unwrap(P: cg)->setCodePICModel(Reloc::PIC_);
435 return false;
436 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
437 unwrap(P: cg)->setCodePICModel(Reloc::DynamicNoPIC);
438 return false;
439 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
440 unwrap(P: cg)->setCodePICModel(std::nullopt);
441 return false;
442 }
443 sLastErrorString = "Unknown PIC model";
444 return true;
445}
446
447void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
448 return unwrap(P: cg)->setCpu(cpu);
449}
450
451void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
452 // In here only for backwards compatibility. We use MC now.
453}
454
455void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
456 int nargs) {
457 // In here only for backwards compatibility. We use MC now.
458}
459
460void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
461 const char *symbol) {
462 unwrap(P: cg)->addMustPreserveSymbol(Sym: symbol);
463}
464
465static void maybeParseOptions(lto_code_gen_t cg) {
466 if (optionParsingState != OptParsingState::Done) {
467 // Parse options if any were set by the lto_codegen_debug_options* function.
468 LibLTOCodeGenerator *CG = unwrap(P: cg);
469 CG->parseCodeGenDebugOptions();
470 // Later code generators in a local context copy the options from
471 // LTOContext.
472 if (CG->OwnedContext)
473 LTOContext->getLibraryOptions().assign(
474 Other: CG->getContext().getLibraryOptions());
475 // The target options were read when the generator was created. Read them
476 // again to pick up the options that were just parsed, unless
477 // lto_set_debug_options already parsed them before that.
478 if (optionParsingState == OptParsingState::NotParsed)
479 CG->setTargetOptions(
480 codegen::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), TheTriple: Triple()));
481 lto_add_attrs(cg);
482 optionParsingState = OptParsingState::Done;
483 }
484}
485
486bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
487 maybeParseOptions(cg);
488 return !unwrap(P: cg)->writeMergedModules(Path: path);
489}
490
491const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
492 maybeParseOptions(cg);
493 LibLTOCodeGenerator *CG = unwrap(P: cg);
494 CG->NativeObjectFile = CG->compile();
495 if (!CG->NativeObjectFile)
496 return nullptr;
497 *length = CG->NativeObjectFile->getBufferSize();
498 return CG->NativeObjectFile->getBufferStart();
499}
500
501bool lto_codegen_optimize(lto_code_gen_t cg) {
502 maybeParseOptions(cg);
503 return !unwrap(P: cg)->optimize();
504}
505
506const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
507 maybeParseOptions(cg);
508 LibLTOCodeGenerator *CG = unwrap(P: cg);
509 CG->NativeObjectFile = CG->compileOptimized();
510 if (!CG->NativeObjectFile)
511 return nullptr;
512 *length = CG->NativeObjectFile->getBufferSize();
513 return CG->NativeObjectFile->getBufferStart();
514}
515
516bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
517 maybeParseOptions(cg);
518 return !unwrap(P: cg)->compile_to_file(Name: name);
519}
520
521static void parseDebugOptions(ArrayRef<const char *> Options) {
522 lto_initialize();
523 std::vector<const char *> CodegenArgv(1, "libLTO");
524 append_range(C&: CodegenArgv, R&: Options);
525 cl::parseCommandLineOptions(Context&: LTOContext->getLibraryOptions(),
526 ToolOptions: codegen::getToolOptions(), Args: CodegenArgv);
527}
528
529void lto_set_debug_options(const char *const *options, int number) {
530 assert(optionParsingState == OptParsingState::NotParsed &&
531 "option processing already happened");
532 parseDebugOptions(Options: ArrayRef(options, number));
533 optionParsingState = OptParsingState::Early;
534}
535
536void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
537 assert(optionParsingState != OptParsingState::Early &&
538 "early option processing already happened");
539 SmallVector<StringRef, 4> Options;
540 for (std::pair<StringRef, StringRef> o = getToken(Source: opt); !o.first.empty();
541 o = getToken(Source: o.second))
542 Options.push_back(Elt: o.first);
543
544 unwrap(P: cg)->setCodeGenDebugOptions(Options);
545}
546
547void lto_codegen_debug_options_array(lto_code_gen_t cg,
548 const char *const *options, int number) {
549 assert(optionParsingState != OptParsingState::Early &&
550 "early option processing already happened");
551 SmallVector<StringRef, 4> Options(ArrayRef(options, number));
552 unwrap(P: cg)->setCodeGenDebugOptions(ArrayRef(Options));
553}
554
555unsigned int lto_api_version() { return LTO_API_VERSION; }
556
557void lto_codegen_set_should_internalize(lto_code_gen_t cg,
558 bool ShouldInternalize) {
559 unwrap(P: cg)->setShouldInternalize(ShouldInternalize);
560}
561
562void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
563 lto_bool_t ShouldEmbedUselists) {
564 unwrap(P: cg)->setShouldEmbedUselists(ShouldEmbedUselists);
565}
566
567lto_bool_t lto_module_has_ctor_dtor(lto_module_t mod) {
568 return unwrap(P: mod)->hasCtorDtor();
569}
570
571// ThinLTO API below
572
573thinlto_code_gen_t thinlto_create_codegen(void) {
574 lto_initialize();
575 ThinLTOCodeGenerator *CodeGen =
576 new ThinLTOCodeGenerator(LTOContext->getLibraryOptions());
577 CodeGen->setMllvmArgs(ThinLTOMllvmArgs);
578 CodeGen->setTargetOptions(
579 codegen::getTargetOptions(LibraryOptions: LTOContext->getLibraryOptions(), TheTriple: Triple()));
580 CodeGen->setFreestanding(EnableFreestanding);
581
582 if (OptLevel.getNumOccurrences()) {
583 if (OptLevel < '0' || OptLevel > '3')
584 report_fatal_error(reason: "Optimization level must be between 0 and 3");
585 CodeGen->setOptLevel(OptLevel - '0');
586 std::optional<CodeGenOptLevel> CGOptLevelOrNone =
587 CodeGenOpt::getLevel(OL: OptLevel - '0');
588 assert(CGOptLevelOrNone);
589 CodeGen->setCodeGenOptLevel(*CGOptLevelOrNone);
590 }
591 if (!ThinLTOCacheDir.empty()) {
592 auto Err = llvm::sys::fs::create_directories(path: ThinLTOCacheDir);
593 if (Err)
594 report_fatal_error(reason: Twine("Unable to create thinLTO cache directory: ") +
595 Err.message());
596 bool result;
597 Err = llvm::sys::fs::is_directory(path: ThinLTOCacheDir, result);
598 if (Err || !result)
599 report_fatal_error(reason: Twine("Unable to get status of thinLTO cache path or "
600 "path is not a directory: ") +
601 Err.message());
602 CodeGen->setCacheDir(ThinLTOCacheDir);
603
604 CodeGen->setCachePruningInterval(ThinLTOCachePruningInterval);
605 CodeGen->setCacheEntryExpiration(ThinLTOCacheEntryExpiration);
606 CodeGen->setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
607 CodeGen->setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
608 }
609
610 return wrap(P: CodeGen);
611}
612
613void thinlto_codegen_dispose(thinlto_code_gen_t cg) { delete unwrap(P: cg); }
614
615void thinlto_codegen_add_module(thinlto_code_gen_t cg, const char *Identifier,
616 const char *Data, int Length) {
617 unwrap(P: cg)->addModule(Identifier, Data: StringRef(Data, Length));
618}
619
620void thinlto_codegen_process(thinlto_code_gen_t cg) { unwrap(P: cg)->run(); }
621
622unsigned int thinlto_module_get_num_objects(thinlto_code_gen_t cg) {
623 return unwrap(P: cg)->getProducedBinaries().size();
624}
625LTOObjectBuffer thinlto_module_get_object(thinlto_code_gen_t cg,
626 unsigned int index) {
627 assert(index < unwrap(cg)->getProducedBinaries().size() && "Index overflow");
628 auto &MemBuffer = unwrap(P: cg)->getProducedBinaries()[index];
629 return LTOObjectBuffer{.Buffer: MemBuffer->getBufferStart(),
630 .Size: MemBuffer->getBufferSize()};
631}
632
633unsigned int thinlto_module_get_num_object_files(thinlto_code_gen_t cg) {
634 return unwrap(P: cg)->getProducedBinaryFiles().size();
635}
636const char *thinlto_module_get_object_file(thinlto_code_gen_t cg,
637 unsigned int index) {
638 assert(index < unwrap(cg)->getProducedBinaryFiles().size() &&
639 "Index overflow");
640 return unwrap(P: cg)->getProducedBinaryFiles()[index].c_str();
641}
642
643void thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,
644 lto_bool_t disable) {
645 unwrap(P: cg)->disableCodeGen(Disable: disable);
646}
647
648void thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,
649 lto_bool_t CodeGenOnly) {
650 unwrap(P: cg)->setCodeGenOnly(CodeGenOnly);
651}
652
653void thinlto_debug_options(const char *const *options, int number) {
654 // If options were requested, parse and retain them.
655 if (number && options) {
656 parseDebugOptions(Options: ArrayRef(options, number));
657 ThinLTOMllvmArgs.assign(first: options, last: options + number);
658 }
659}
660
661lto_bool_t lto_module_is_thinlto(lto_module_t mod) {
662 return unwrap(P: mod)->isThinLTO();
663}
664
665void thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,
666 const char *Name, int Length) {
667 unwrap(P: cg)->preserveSymbol(Name: StringRef(Name, Length));
668}
669
670void thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,
671 const char *Name, int Length) {
672 unwrap(P: cg)->crossReferenceSymbol(Name: StringRef(Name, Length));
673}
674
675void thinlto_codegen_set_cpu(thinlto_code_gen_t cg, const char *cpu) {
676 return unwrap(P: cg)->setCpu(cpu);
677}
678
679void thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,
680 const char *cache_dir) {
681 return unwrap(P: cg)->setCacheDir(cache_dir);
682}
683
684void thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,
685 int interval) {
686 return unwrap(P: cg)->setCachePruningInterval(interval);
687}
688
689void thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,
690 unsigned expiration) {
691 return unwrap(P: cg)->setCacheEntryExpiration(expiration);
692}
693
694void thinlto_codegen_set_final_cache_size_relative_to_available_space(
695 thinlto_code_gen_t cg, unsigned Percentage) {
696 return unwrap(P: cg)->setMaxCacheSizeRelativeToAvailableSpace(Percentage);
697}
698
699void thinlto_codegen_set_cache_size_bytes(
700 thinlto_code_gen_t cg, unsigned MaxSizeBytes) {
701 return unwrap(P: cg)->setCacheMaxSizeBytes(MaxSizeBytes);
702}
703
704void thinlto_codegen_set_cache_size_megabytes(
705 thinlto_code_gen_t cg, unsigned MaxSizeMegabytes) {
706 uint64_t MaxSizeBytes = MaxSizeMegabytes;
707 MaxSizeBytes *= 1024 * 1024;
708 return unwrap(P: cg)->setCacheMaxSizeBytes(MaxSizeBytes);
709}
710
711void thinlto_codegen_set_cache_size_files(
712 thinlto_code_gen_t cg, unsigned MaxSizeFiles) {
713 return unwrap(P: cg)->setCacheMaxSizeFiles(MaxSizeFiles);
714}
715
716void thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,
717 const char *save_temps_dir) {
718 return unwrap(P: cg)->setSaveTempsDir(save_temps_dir);
719}
720
721void thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,
722 const char *save_temps_dir) {
723 unwrap(P: cg)->setGeneratedObjectsDirectory(save_temps_dir);
724}
725
726lto_bool_t thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,
727 lto_codegen_model model) {
728 switch (model) {
729 case LTO_CODEGEN_PIC_MODEL_STATIC:
730 unwrap(P: cg)->setCodePICModel(Reloc::Static);
731 return false;
732 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
733 unwrap(P: cg)->setCodePICModel(Reloc::PIC_);
734 return false;
735 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
736 unwrap(P: cg)->setCodePICModel(Reloc::DynamicNoPIC);
737 return false;
738 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
739 unwrap(P: cg)->setCodePICModel(std::nullopt);
740 return false;
741 }
742 sLastErrorString = "Unknown PIC model";
743 return true;
744}
745
746DEFINE_SIMPLE_CONVERSION_FUNCTIONS(lto::InputFile, lto_input_t)
747
748lto_input_t lto_input_create(const void *buffer, size_t buffer_size, const char *path) {
749 return wrap(P: LTOModule::createInputFile(buffer, buffer_size, path, out_error&: sLastErrorString));
750}
751
752void lto_input_dispose(lto_input_t input) {
753 delete unwrap(P: input);
754}
755
756extern unsigned lto_input_get_num_dependent_libraries(lto_input_t input) {
757 return LTOModule::getDependentLibraryCount(input: unwrap(P: input));
758}
759
760extern const char *lto_input_get_dependent_library(lto_input_t input,
761 size_t index,
762 size_t *size) {
763 return LTOModule::getDependentLibrary(input: unwrap(P: input), index, size);
764}
765
766extern const char *const *lto_runtime_lib_symbols_list(size_t *size) {
767 *size = RuntimeLibcallSymbols.size();
768 return RuntimeLibcallSymbols.data();
769}
770
771extern const char *const *
772lto_runtime_lib_symbols_list_for_triple(const char *TS, size_t *size) {
773 static StringMap<SmallVector<const char *>> RTLibcallSymMap;
774 Triple TT(TS);
775 auto [It, Inserted] = RTLibcallSymMap.try_emplace(Key: TT.normalize());
776 if (Inserted)
777 It->second = lto::LTO::getRuntimeLibcallSymbols(TT);
778 *size = It->second.size();
779 return It->second.data();
780}
781