xref: /llvm-project-15.0.7/llvm/tools/lto/lto.cpp (revision b50df911)
1 //===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm-c/lto.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Bitcode/ReaderWriter.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/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 
30 // extra command-line flags needed for LTOCodeGenerator
31 static cl::opt<char>
32 OptLevel("O",
33          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
34                   "(default = '-O2')"),
35          cl::Prefix,
36          cl::ZeroOrMore,
37          cl::init('2'));
38 
39 static cl::opt<bool>
40 DisableInline("disable-inlining", cl::init(false),
41   cl::desc("Do not run the inliner pass"));
42 
43 static cl::opt<bool>
44 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
45   cl::desc("Do not run the GVN load PRE pass"));
46 
47 static cl::opt<bool>
48 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
49   cl::desc("Do not run loop or slp vectorization during LTO"));
50 
51 #ifdef NDEBUG
52 static bool VerifyByDefault = false;
53 #else
54 static bool VerifyByDefault = true;
55 #endif
56 
57 static cl::opt<bool> DisableVerify(
58     "disable-llvm-verifier", cl::init(!VerifyByDefault),
59     cl::desc("Don't run the LLVM verifier during the optimization pipeline"));
60 
61 // Holds most recent error string.
62 // *** Not thread safe ***
63 static std::string sLastErrorString;
64 
65 // Holds the initialization state of the LTO module.
66 // *** Not thread safe ***
67 static bool initialized = false;
68 
69 // Holds the command-line option parsing state of the LTO module.
70 static bool parsedOptions = false;
71 
72 static LLVMContext *LTOContext = nullptr;
73 
74 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
75   if (DI.getSeverity() != DS_Error) {
76     DiagnosticPrinterRawOStream DP(errs());
77     DI.print(DP);
78     errs() << '\n';
79     return;
80   }
81   sLastErrorString = "";
82   {
83     raw_string_ostream Stream(sLastErrorString);
84     DiagnosticPrinterRawOStream DP(Stream);
85     DI.print(DP);
86   }
87 }
88 
89 // Initialize the configured targets if they have not been initialized.
90 static void lto_initialize() {
91   if (!initialized) {
92 #ifdef LLVM_ON_WIN32
93     // Dialog box on crash disabling doesn't work across DLL boundaries, so do
94     // it here.
95     llvm::sys::DisableSystemDialogsOnCrash();
96 #endif
97 
98     InitializeAllTargetInfos();
99     InitializeAllTargets();
100     InitializeAllTargetMCs();
101     InitializeAllAsmParsers();
102     InitializeAllAsmPrinters();
103     InitializeAllDisassemblers();
104 
105     static LLVMContext Context;
106     LTOContext = &Context;
107     LTOContext->setDiagnosticHandler(diagnosticHandler, nullptr, true);
108     initialized = true;
109   }
110 }
111 
112 namespace {
113 
114 static void handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,
115                                    const char *Msg, void *) {
116   sLastErrorString = Msg;
117 }
118 
119 // This derived class owns the native object file. This helps implement the
120 // libLTO API semantics, which require that the code generator owns the object
121 // file.
122 struct LibLTOCodeGenerator : LTOCodeGenerator {
123   LibLTOCodeGenerator() : LTOCodeGenerator(*LTOContext) { init(); }
124   LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
125       : LTOCodeGenerator(*Context), OwnedContext(std::move(Context)) {
126     init();
127   }
128 
129   // Reset the module first in case MergedModule is created in OwnedContext.
130   // Module must be destructed before its context gets destructed.
131   ~LibLTOCodeGenerator() { resetMergedModule(); }
132 
133   void init() { setDiagnosticHandler(handleLibLTODiagnostic, nullptr); }
134 
135   std::unique_ptr<MemoryBuffer> NativeObjectFile;
136   std::unique_ptr<LLVMContext> OwnedContext;
137 };
138 
139 }
140 
141 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
142 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThinLTOCodeGenerator, thinlto_code_gen_t)
143 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
144 
145 // Convert the subtarget features into a string to pass to LTOCodeGenerator.
146 static void lto_add_attrs(lto_code_gen_t cg) {
147   LTOCodeGenerator *CG = unwrap(cg);
148   if (MAttrs.size()) {
149     std::string attrs;
150     for (unsigned i = 0; i < MAttrs.size(); ++i) {
151       if (i > 0)
152         attrs.append(",");
153       attrs.append(MAttrs[i]);
154     }
155 
156     CG->setAttr(attrs.c_str());
157   }
158 
159   if (OptLevel < '0' || OptLevel > '3')
160     report_fatal_error("Optimization level must be between 0 and 3");
161   CG->setOptLevel(OptLevel - '0');
162 }
163 
164 extern const char* lto_get_version() {
165   return LTOCodeGenerator::getVersionString();
166 }
167 
168 const char* lto_get_error_message() {
169   return sLastErrorString.c_str();
170 }
171 
172 bool lto_module_is_object_file(const char* path) {
173   return LTOModule::isBitcodeFile(StringRef(path));
174 }
175 
176 bool 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(path);
179   if (!Buffer)
180     return false;
181   return LTOModule::isBitcodeForTarget(Buffer->get(),
182                                        StringRef(target_triplet_prefix));
183 }
184 
185 bool 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   return llvm::isBitcodeContainingObjCCategory(*Buffer, Ctx);
191 }
192 
193 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
194   return LTOModule::isBitcodeFile(mem, length);
195 }
196 
197 bool
198 lto_module_is_object_file_in_memory_for_target(const void* mem,
199                                             size_t length,
200                                             const char* target_triplet_prefix) {
201   std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
202   if (!buffer)
203     return false;
204   return LTOModule::isBitcodeForTarget(buffer.get(),
205                                        StringRef(target_triplet_prefix));
206 }
207 
208 lto_module_t lto_module_create(const char* path) {
209   lto_initialize();
210   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
211   ErrorOr<std::unique_ptr<LTOModule>> M =
212       LTOModule::createFromFile(*LTOContext, StringRef(path), Options);
213   if (!M)
214     return nullptr;
215   return wrap(M->release());
216 }
217 
218 lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
219   lto_initialize();
220   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
221   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFile(
222       *LTOContext, fd, StringRef(path), size, Options);
223   if (!M)
224     return nullptr;
225   return wrap(M->release());
226 }
227 
228 lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
229                                                  size_t file_size,
230                                                  size_t map_size,
231                                                  off_t offset) {
232   lto_initialize();
233   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
234   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFileSlice(
235       *LTOContext, fd, StringRef(path), map_size, offset, Options);
236   if (!M)
237     return nullptr;
238   return wrap(M->release());
239 }
240 
241 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
242   lto_initialize();
243   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
244   ErrorOr<std::unique_ptr<LTOModule>> M =
245       LTOModule::createFromBuffer(*LTOContext, mem, length, Options);
246   if (!M)
247     return nullptr;
248   return wrap(M->release());
249 }
250 
251 lto_module_t lto_module_create_from_memory_with_path(const void* mem,
252                                                      size_t length,
253                                                      const char *path) {
254   lto_initialize();
255   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
256   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
257       *LTOContext, mem, length, Options, StringRef(path));
258   if (!M)
259     return nullptr;
260   return wrap(M->release());
261 }
262 
263 lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
264                                                 const char *path) {
265   lto_initialize();
266   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
267 
268   // Create a local context. Ownership will be transfered to LTOModule.
269   std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
270   Context->setDiagnosticHandler(diagnosticHandler, nullptr, true);
271 
272   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createInLocalContext(
273       std::move(Context), 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_codegen_context(const void *mem,
280                                                   size_t length,
281                                                   const char *path,
282                                                   lto_code_gen_t cg) {
283   lto_initialize();
284   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
285   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
286       unwrap(cg)->getContext(), mem, length, Options, StringRef(path));
287   return wrap(M->release());
288 }
289 
290 void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
291 
292 const char* lto_module_get_target_triple(lto_module_t mod) {
293   return unwrap(mod)->getTargetTriple().c_str();
294 }
295 
296 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
297   return unwrap(mod)->setTargetTriple(StringRef(triple));
298 }
299 
300 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
301   return unwrap(mod)->getSymbolCount();
302 }
303 
304 const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
305   return unwrap(mod)->getSymbolName(index).data();
306 }
307 
308 lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
309                                                       unsigned int index) {
310   return unwrap(mod)->getSymbolAttributes(index);
311 }
312 
313 const char* lto_module_get_linkeropts(lto_module_t mod) {
314   return unwrap(mod)->getLinkerOpts().data();
315 }
316 
317 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
318                                         lto_diagnostic_handler_t diag_handler,
319                                         void *ctxt) {
320   unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
321 }
322 
323 static lto_code_gen_t createCodeGen(bool InLocalContext) {
324   lto_initialize();
325 
326   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
327 
328   LibLTOCodeGenerator *CodeGen =
329       InLocalContext ? new LibLTOCodeGenerator(make_unique<LLVMContext>())
330                      : new LibLTOCodeGenerator();
331   CodeGen->setTargetOptions(Options);
332   return wrap(CodeGen);
333 }
334 
335 lto_code_gen_t lto_codegen_create(void) {
336   return createCodeGen(/* InLocalContext */ false);
337 }
338 
339 lto_code_gen_t lto_codegen_create_in_local_context(void) {
340   return createCodeGen(/* InLocalContext */ true);
341 }
342 
343 void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
344 
345 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
346   return !unwrap(cg)->addModule(unwrap(mod));
347 }
348 
349 void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
350   unwrap(cg)->setModule(std::unique_ptr<LTOModule>(unwrap(mod)));
351 }
352 
353 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
354   unwrap(cg)->setDebugInfo(debug);
355   return false;
356 }
357 
358 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
359   switch (model) {
360   case LTO_CODEGEN_PIC_MODEL_STATIC:
361     unwrap(cg)->setCodePICModel(Reloc::Static);
362     return false;
363   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
364     unwrap(cg)->setCodePICModel(Reloc::PIC_);
365     return false;
366   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
367     unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
368     return false;
369   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
370     unwrap(cg)->setCodePICModel(None);
371     return false;
372   }
373   sLastErrorString = "Unknown PIC model";
374   return true;
375 }
376 
377 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
378   return unwrap(cg)->setCpu(cpu);
379 }
380 
381 void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
382   // In here only for backwards compatibility. We use MC now.
383 }
384 
385 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
386                                     int nargs) {
387   // In here only for backwards compatibility. We use MC now.
388 }
389 
390 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
391                                           const char *symbol) {
392   unwrap(cg)->addMustPreserveSymbol(symbol);
393 }
394 
395 static void maybeParseOptions(lto_code_gen_t cg) {
396   if (!parsedOptions) {
397     unwrap(cg)->parseCodeGenDebugOptions();
398     lto_add_attrs(cg);
399     parsedOptions = true;
400   }
401 }
402 
403 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
404   maybeParseOptions(cg);
405   return !unwrap(cg)->writeMergedModules(path);
406 }
407 
408 const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
409   maybeParseOptions(cg);
410   LibLTOCodeGenerator *CG = unwrap(cg);
411   CG->NativeObjectFile =
412       CG->compile(DisableVerify, DisableInline, DisableGVNLoadPRE,
413                   DisableLTOVectorization);
414   if (!CG->NativeObjectFile)
415     return nullptr;
416   *length = CG->NativeObjectFile->getBufferSize();
417   return CG->NativeObjectFile->getBufferStart();
418 }
419 
420 bool lto_codegen_optimize(lto_code_gen_t cg) {
421   maybeParseOptions(cg);
422   return !unwrap(cg)->optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
423                                DisableLTOVectorization);
424 }
425 
426 const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
427   maybeParseOptions(cg);
428   LibLTOCodeGenerator *CG = unwrap(cg);
429   CG->NativeObjectFile = CG->compileOptimized();
430   if (!CG->NativeObjectFile)
431     return nullptr;
432   *length = CG->NativeObjectFile->getBufferSize();
433   return CG->NativeObjectFile->getBufferStart();
434 }
435 
436 bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
437   maybeParseOptions(cg);
438   return !unwrap(cg)->compile_to_file(
439       name, DisableVerify, DisableInline, DisableGVNLoadPRE,
440       DisableLTOVectorization);
441 }
442 
443 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
444   unwrap(cg)->setCodeGenDebugOptions(opt);
445 }
446 
447 unsigned int lto_api_version() { return LTO_API_VERSION; }
448 
449 void lto_codegen_set_should_internalize(lto_code_gen_t cg,
450                                         bool ShouldInternalize) {
451   unwrap(cg)->setShouldInternalize(ShouldInternalize);
452 }
453 
454 void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
455                                            lto_bool_t ShouldEmbedUselists) {
456   unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);
457 }
458 
459 // ThinLTO API below
460 
461 thinlto_code_gen_t thinlto_create_codegen(void) {
462   lto_initialize();
463   ThinLTOCodeGenerator *CodeGen = new ThinLTOCodeGenerator();
464   CodeGen->setTargetOptions(InitTargetOptionsFromCodeGenFlags());
465 
466   return wrap(CodeGen);
467 }
468 
469 void thinlto_codegen_dispose(thinlto_code_gen_t cg) { delete unwrap(cg); }
470 
471 void thinlto_codegen_add_module(thinlto_code_gen_t cg, const char *Identifier,
472                                 const char *Data, int Length) {
473   unwrap(cg)->addModule(Identifier, StringRef(Data, Length));
474 }
475 
476 void thinlto_codegen_process(thinlto_code_gen_t cg) { unwrap(cg)->run(); }
477 
478 unsigned int thinlto_module_get_num_objects(thinlto_code_gen_t cg) {
479   return unwrap(cg)->getProducedBinaries().size();
480 }
481 LTOObjectBuffer thinlto_module_get_object(thinlto_code_gen_t cg,
482                                           unsigned int index) {
483   assert(index < unwrap(cg)->getProducedBinaries().size() && "Index overflow");
484   auto &MemBuffer = unwrap(cg)->getProducedBinaries()[index];
485   return LTOObjectBuffer{MemBuffer->getBufferStart(),
486                          MemBuffer->getBufferSize()};
487 }
488 
489 void thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,
490                                      lto_bool_t disable) {
491   unwrap(cg)->disableCodeGen(disable);
492 }
493 
494 void thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,
495                                       lto_bool_t CodeGenOnly) {
496   unwrap(cg)->setCodeGenOnly(CodeGenOnly);
497 }
498 
499 void thinlto_debug_options(const char *const *options, int number) {
500   // if options were requested, set them
501   if (number && options) {
502     std::vector<const char *> CodegenArgv(1, "libLTO");
503     for (auto Arg : ArrayRef<const char *>(options, number))
504       CodegenArgv.push_back(Arg);
505     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
506   }
507 }
508 
509 lto_bool_t lto_module_is_thinlto(lto_module_t mod) {
510   return unwrap(mod)->isThinLTO();
511 }
512 
513 void thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,
514                                               const char *Name, int Length) {
515   unwrap(cg)->preserveSymbol(StringRef(Name, Length));
516 }
517 
518 void thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,
519                                                  const char *Name, int Length) {
520   unwrap(cg)->crossReferenceSymbol(StringRef(Name, Length));
521 }
522 
523 void thinlto_codegen_set_cpu(thinlto_code_gen_t cg, const char *cpu) {
524   return unwrap(cg)->setCpu(cpu);
525 }
526 
527 void thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,
528                                    const char *cache_dir) {
529   return unwrap(cg)->setCacheDir(cache_dir);
530 }
531 
532 void thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,
533                                                 int interval) {
534   return unwrap(cg)->setCachePruningInterval(interval);
535 }
536 
537 void thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,
538                                                 unsigned expiration) {
539   return unwrap(cg)->setCacheEntryExpiration(expiration);
540 }
541 
542 void thinlto_codegen_set_final_cache_size_relative_to_available_space(
543     thinlto_code_gen_t cg, unsigned Percentage) {
544   return unwrap(cg)->setMaxCacheSizeRelativeToAvailableSpace(Percentage);
545 }
546 
547 void thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,
548                                        const char *save_temps_dir) {
549   return unwrap(cg)->setSaveTempsDir(save_temps_dir);
550 }
551 
552 lto_bool_t thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,
553                                          lto_codegen_model model) {
554   switch (model) {
555   case LTO_CODEGEN_PIC_MODEL_STATIC:
556     unwrap(cg)->setCodePICModel(Reloc::Static);
557     return false;
558   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
559     unwrap(cg)->setCodePICModel(Reloc::PIC_);
560     return false;
561   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
562     unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
563     return false;
564   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
565     unwrap(cg)->setCodePICModel(None);
566     return false;
567   }
568   sLastErrorString = "Unknown PIC model";
569   return true;
570 }
571