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