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

source code of llvm/tools/lto/lto.cpp