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