LTO.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. //===- LTO.cpp ------------------------------------------------------------===//
  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. #include "LTO.h"
  9. #include "Config.h"
  10. #include "InputFiles.h"
  11. #include "Symbols.h"
  12. #include "lld/Common/Args.h"
  13. #include "lld/Common/ErrorHandler.h"
  14. #include "lld/Common/Strings.h"
  15. #include "lld/Common/TargetOptionsCommandFlags.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/IR/DiagnosticPrinter.h"
  21. #include "llvm/LTO/Caching.h"
  22. #include "llvm/LTO/Config.h"
  23. #include "llvm/LTO/LTO.h"
  24. #include "llvm/Object/SymbolicFile.h"
  25. #include "llvm/Support/CodeGen.h"
  26. #include "llvm/Support/Error.h"
  27. #include "llvm/Support/FileSystem.h"
  28. #include "llvm/Support/MemoryBuffer.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <algorithm>
  31. #include <cstddef>
  32. #include <memory>
  33. #include <string>
  34. #include <system_error>
  35. #include <vector>
  36. using namespace llvm;
  37. namespace lld {
  38. namespace wasm {
  39. static std::unique_ptr<lto::LTO> createLTO() {
  40. lto::Config c;
  41. c.Options = initTargetOptionsFromCodeGenFlags();
  42. // Always emit a section per function/data with LTO.
  43. c.Options.FunctionSections = true;
  44. c.Options.DataSections = true;
  45. c.DisableVerify = config->disableVerify;
  46. c.DiagHandler = diagnosticHandler;
  47. c.OptLevel = config->ltoo;
  48. c.MAttrs = getMAttrs();
  49. c.CGOptLevel = args::getCGOptLevel(config->ltoo);
  50. if (config->relocatable)
  51. c.RelocModel = None;
  52. else if (config->isPic)
  53. c.RelocModel = Reloc::PIC_;
  54. else
  55. c.RelocModel = Reloc::Static;
  56. if (config->saveTemps)
  57. checkError(c.addSaveTemps(config->outputFile.str() + ".",
  58. /*UseInputModulePath*/ true));
  59. lto::ThinBackend backend;
  60. if (config->thinLTOJobs != -1U)
  61. backend = lto::createInProcessThinBackend(config->thinLTOJobs);
  62. return std::make_unique<lto::LTO>(std::move(c), backend,
  63. config->ltoPartitions);
  64. }
  65. BitcodeCompiler::BitcodeCompiler() : ltoObj(createLTO()) {}
  66. BitcodeCompiler::~BitcodeCompiler() = default;
  67. static void undefine(Symbol *s) {
  68. if (auto f = dyn_cast<DefinedFunction>(s))
  69. replaceSymbol<UndefinedFunction>(f, f->getName(), "", "", 0, f->getFile(),
  70. f->signature);
  71. else if (isa<DefinedData>(s))
  72. replaceSymbol<UndefinedData>(s, s->getName(), 0, s->getFile());
  73. else
  74. llvm_unreachable("unexpected symbol kind");
  75. }
  76. void BitcodeCompiler::add(BitcodeFile &f) {
  77. lto::InputFile &obj = *f.obj;
  78. unsigned symNum = 0;
  79. ArrayRef<Symbol *> syms = f.getSymbols();
  80. std::vector<lto::SymbolResolution> resols(syms.size());
  81. // Provide a resolution to the LTO API for each symbol.
  82. for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
  83. Symbol *sym = syms[symNum];
  84. lto::SymbolResolution &r = resols[symNum];
  85. ++symNum;
  86. // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
  87. // reports two symbols for module ASM defined. Without this check, lld
  88. // flags an undefined in IR with a definition in ASM as prevailing.
  89. // Once IRObjectFile is fixed to report only one symbol this hack can
  90. // be removed.
  91. r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
  92. r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj ||
  93. sym->isNoStrip() ||
  94. (r.Prevailing && sym->isExported());
  95. if (r.Prevailing)
  96. undefine(sym);
  97. // We tell LTO to not apply interprocedural optimization for wrapped
  98. // (with --wrap) symbols because otherwise LTO would inline them while
  99. // their values are still not final.
  100. r.LinkerRedefined = !sym->canInline;
  101. }
  102. checkError(ltoObj->add(std::move(f.obj), resols));
  103. }
  104. // Merge all the bitcode files we have seen, codegen the result
  105. // and return the resulting objects.
  106. std::vector<StringRef> BitcodeCompiler::compile() {
  107. unsigned maxTasks = ltoObj->getMaxTasks();
  108. buf.resize(maxTasks);
  109. files.resize(maxTasks);
  110. // The --thinlto-cache-dir option specifies the path to a directory in which
  111. // to cache native object files for ThinLTO incremental builds. If a path was
  112. // specified, configure LTO to use it as the cache directory.
  113. lto::NativeObjectCache cache;
  114. if (!config->thinLTOCacheDir.empty())
  115. cache = check(
  116. lto::localCache(config->thinLTOCacheDir,
  117. [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
  118. files[task] = std::move(mb);
  119. }));
  120. checkError(ltoObj->run(
  121. [&](size_t task) {
  122. return std::make_unique<lto::NativeObjectStream>(
  123. std::make_unique<raw_svector_ostream>(buf[task]));
  124. },
  125. cache));
  126. if (!config->thinLTOCacheDir.empty())
  127. pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy);
  128. std::vector<StringRef> ret;
  129. for (unsigned i = 0; i != maxTasks; ++i) {
  130. if (buf[i].empty())
  131. continue;
  132. if (config->saveTemps) {
  133. if (i == 0)
  134. saveBuffer(buf[i], config->outputFile + ".lto.o");
  135. else
  136. saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
  137. }
  138. ret.emplace_back(buf[i].data(), buf[i].size());
  139. }
  140. for (std::unique_ptr<MemoryBuffer> &file : files)
  141. if (file)
  142. ret.push_back(file->getBuffer());
  143. return ret;
  144. }
  145. } // namespace wasm
  146. } // namespace lld