lto.cpp 23 KB

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