PageRenderTime 61ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/llvm/tools/llvm-lto2/llvm-lto2.cpp

https://bitbucket.org/freebsd/freebsd-base
C++ | 443 lines | 345 code | 72 blank | 26 comment | 57 complexity | 00616b91117e342450784107e6410775 MD5 | raw file
  1. //===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
  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 program takes in a list of bitcode files, links them and performs
  10. // link-time optimization according to the provided symbol resolutions using the
  11. // resolution-based LTO interface, and outputs one or more object files.
  12. //
  13. // This program is intended to eventually replace llvm-lto which uses the legacy
  14. // LTO interface.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Bitcode/BitcodeReader.h"
  18. #include "llvm/CodeGen/CommandFlags.inc"
  19. #include "llvm/IR/DiagnosticPrinter.h"
  20. #include "llvm/LTO/Caching.h"
  21. #include "llvm/LTO/LTO.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/InitLLVM.h"
  25. #include "llvm/Support/TargetSelect.h"
  26. #include "llvm/Support/Threading.h"
  27. using namespace llvm;
  28. using namespace lto;
  29. static cl::opt<char>
  30. OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  31. "(default = '-O2')"),
  32. cl::Prefix, cl::ZeroOrMore, cl::init('2'));
  33. static cl::opt<char> CGOptLevel(
  34. "cg-opt-level",
  35. cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
  36. cl::init('2'));
  37. static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
  38. cl::desc("<input bitcode files>"));
  39. static cl::opt<std::string> OutputFilename("o", cl::Required,
  40. cl::desc("Output filename"),
  41. cl::value_desc("filename"));
  42. static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
  43. cl::value_desc("directory"));
  44. static cl::opt<std::string> OptPipeline("opt-pipeline",
  45. cl::desc("Optimizer Pipeline"),
  46. cl::value_desc("pipeline"));
  47. static cl::opt<std::string> AAPipeline("aa-pipeline",
  48. cl::desc("Alias Analysis Pipeline"),
  49. cl::value_desc("aapipeline"));
  50. static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
  51. static cl::opt<bool>
  52. ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
  53. cl::desc("Write out individual index and "
  54. "import files for the "
  55. "distributed backend case"));
  56. static cl::opt<int> Threads("thinlto-threads",
  57. cl::init(llvm::heavyweight_hardware_concurrency()));
  58. static cl::list<std::string> SymbolResolutions(
  59. "r",
  60. cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
  61. "where \"resolution\" is a sequence (which may be empty) of the\n"
  62. "following characters:\n"
  63. " p - prevailing: the linker has chosen this definition of the\n"
  64. " symbol\n"
  65. " l - local: the definition of this symbol is unpreemptable at\n"
  66. " runtime and is known to be in this linkage unit\n"
  67. " x - externally visible: the definition of this symbol is\n"
  68. " visible outside of the LTO unit\n"
  69. "A resolution for each symbol must be specified."),
  70. cl::ZeroOrMore);
  71. static cl::opt<std::string> OverrideTriple(
  72. "override-triple",
  73. cl::desc("Replace target triples in input files with this triple"));
  74. static cl::opt<std::string> DefaultTriple(
  75. "default-triple",
  76. cl::desc(
  77. "Replace unspecified target triples in input files with this triple"));
  78. static cl::opt<bool> RemarksWithHotness(
  79. "pass-remarks-with-hotness",
  80. cl::desc("With PGO, include profile count in optimization remarks"),
  81. cl::Hidden);
  82. static cl::opt<std::string>
  83. RemarksFilename("pass-remarks-output",
  84. cl::desc("Output filename for pass remarks"),
  85. cl::value_desc("filename"));
  86. static cl::opt<std::string>
  87. RemarksPasses("pass-remarks-filter",
  88. cl::desc("Only record optimization remarks from passes whose "
  89. "names match the given regular expression"),
  90. cl::value_desc("regex"));
  91. static cl::opt<std::string> RemarksFormat(
  92. "pass-remarks-format",
  93. cl::desc("The format used for serializing remarks (default: YAML)"),
  94. cl::value_desc("format"), cl::init("yaml"));
  95. static cl::opt<std::string>
  96. SamplePGOFile("lto-sample-profile-file",
  97. cl::desc("Specify a SamplePGO profile file"));
  98. static cl::opt<std::string>
  99. CSPGOFile("lto-cspgo-profile-file",
  100. cl::desc("Specify a context sensitive PGO profile file"));
  101. static cl::opt<bool>
  102. RunCSIRInstr("lto-cspgo-gen",
  103. cl::desc("Run PGO context sensitive IR instrumentation"),
  104. cl::init(false), cl::Hidden);
  105. static cl::opt<bool>
  106. UseNewPM("use-new-pm",
  107. cl::desc("Run LTO passes using the new pass manager"),
  108. cl::init(false), cl::Hidden);
  109. static cl::opt<bool>
  110. DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
  111. cl::desc("Print pass management debugging information"));
  112. static cl::opt<std::string>
  113. StatsFile("stats-file", cl::desc("Filename to write statistics to"));
  114. static void check(Error E, std::string Msg) {
  115. if (!E)
  116. return;
  117. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  118. errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
  119. });
  120. exit(1);
  121. }
  122. template <typename T> static T check(Expected<T> E, std::string Msg) {
  123. if (E)
  124. return std::move(*E);
  125. check(E.takeError(), Msg);
  126. return T();
  127. }
  128. static void check(std::error_code EC, std::string Msg) {
  129. check(errorCodeToError(EC), Msg);
  130. }
  131. template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
  132. if (E)
  133. return std::move(*E);
  134. check(E.getError(), Msg);
  135. return T();
  136. }
  137. static int usage() {
  138. errs() << "Available subcommands: dump-symtab run\n";
  139. return 1;
  140. }
  141. static int run(int argc, char **argv) {
  142. cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
  143. // FIXME: Workaround PR30396 which means that a symbol can appear
  144. // more than once if it is defined in module-level assembly and
  145. // has a GV declaration. We allow (file, symbol) pairs to have multiple
  146. // resolutions and apply them in the order observed.
  147. std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
  148. CommandLineResolutions;
  149. for (std::string R : SymbolResolutions) {
  150. StringRef Rest = R;
  151. StringRef FileName, SymbolName;
  152. std::tie(FileName, Rest) = Rest.split(',');
  153. if (Rest.empty()) {
  154. llvm::errs() << "invalid resolution: " << R << '\n';
  155. return 1;
  156. }
  157. std::tie(SymbolName, Rest) = Rest.split(',');
  158. SymbolResolution Res;
  159. for (char C : Rest) {
  160. if (C == 'p')
  161. Res.Prevailing = true;
  162. else if (C == 'l')
  163. Res.FinalDefinitionInLinkageUnit = true;
  164. else if (C == 'x')
  165. Res.VisibleToRegularObj = true;
  166. else if (C == 'r')
  167. Res.LinkerRedefined = true;
  168. else {
  169. llvm::errs() << "invalid character " << C << " in resolution: " << R
  170. << '\n';
  171. return 1;
  172. }
  173. }
  174. CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
  175. }
  176. std::vector<std::unique_ptr<MemoryBuffer>> MBs;
  177. Config Conf;
  178. Conf.DiagHandler = [](const DiagnosticInfo &DI) {
  179. DiagnosticPrinterRawOStream DP(errs());
  180. DI.print(DP);
  181. errs() << '\n';
  182. if (DI.getSeverity() == DS_Error)
  183. exit(1);
  184. };
  185. Conf.CPU = MCPU;
  186. Conf.Options = InitTargetOptionsFromCodeGenFlags();
  187. Conf.MAttrs = MAttrs;
  188. if (auto RM = getRelocModel())
  189. Conf.RelocModel = *RM;
  190. Conf.CodeModel = getCodeModel();
  191. Conf.DebugPassManager = DebugPassManager;
  192. if (SaveTemps)
  193. check(Conf.addSaveTemps(OutputFilename + "."),
  194. "Config::addSaveTemps failed");
  195. // Optimization remarks.
  196. Conf.RemarksFilename = RemarksFilename;
  197. Conf.RemarksPasses = RemarksPasses;
  198. Conf.RemarksWithHotness = RemarksWithHotness;
  199. Conf.RemarksFormat = RemarksFormat;
  200. Conf.SampleProfile = SamplePGOFile;
  201. Conf.CSIRProfile = CSPGOFile;
  202. Conf.RunCSIRInstr = RunCSIRInstr;
  203. // Run a custom pipeline, if asked for.
  204. Conf.OptPipeline = OptPipeline;
  205. Conf.AAPipeline = AAPipeline;
  206. Conf.OptLevel = OptLevel - '0';
  207. Conf.UseNewPM = UseNewPM;
  208. switch (CGOptLevel) {
  209. case '0':
  210. Conf.CGOptLevel = CodeGenOpt::None;
  211. break;
  212. case '1':
  213. Conf.CGOptLevel = CodeGenOpt::Less;
  214. break;
  215. case '2':
  216. Conf.CGOptLevel = CodeGenOpt::Default;
  217. break;
  218. case '3':
  219. Conf.CGOptLevel = CodeGenOpt::Aggressive;
  220. break;
  221. default:
  222. llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
  223. return 1;
  224. }
  225. if (FileType.getNumOccurrences())
  226. Conf.CGFileType = FileType;
  227. Conf.OverrideTriple = OverrideTriple;
  228. Conf.DefaultTriple = DefaultTriple;
  229. Conf.StatsFile = StatsFile;
  230. ThinBackend Backend;
  231. if (ThinLTODistributedIndexes)
  232. Backend = createWriteIndexesThinBackend(/* OldPrefix */ "",
  233. /* NewPrefix */ "",
  234. /* ShouldEmitImportsFiles */ true,
  235. /* LinkedObjectsFile */ nullptr,
  236. /* OnWrite */ {});
  237. else
  238. Backend = createInProcessThinBackend(Threads);
  239. LTO Lto(std::move(Conf), std::move(Backend));
  240. bool HasErrors = false;
  241. for (std::string F : InputFilenames) {
  242. std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
  243. std::unique_ptr<InputFile> Input =
  244. check(InputFile::create(MB->getMemBufferRef()), F);
  245. std::vector<SymbolResolution> Res;
  246. for (const InputFile::Symbol &Sym : Input->symbols()) {
  247. auto I = CommandLineResolutions.find({F, Sym.getName()});
  248. if (I == CommandLineResolutions.end()) {
  249. llvm::errs() << argv[0] << ": missing symbol resolution for " << F
  250. << ',' << Sym.getName() << '\n';
  251. HasErrors = true;
  252. } else {
  253. Res.push_back(I->second.front());
  254. I->second.pop_front();
  255. if (I->second.empty())
  256. CommandLineResolutions.erase(I);
  257. }
  258. }
  259. if (HasErrors)
  260. continue;
  261. MBs.push_back(std::move(MB));
  262. check(Lto.add(std::move(Input), Res), F);
  263. }
  264. if (!CommandLineResolutions.empty()) {
  265. HasErrors = true;
  266. for (auto UnusedRes : CommandLineResolutions)
  267. llvm::errs() << argv[0] << ": unused symbol resolution for "
  268. << UnusedRes.first.first << ',' << UnusedRes.first.second
  269. << '\n';
  270. }
  271. if (HasErrors)
  272. return 1;
  273. auto AddStream =
  274. [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
  275. std::string Path = OutputFilename + "." + utostr(Task);
  276. std::error_code EC;
  277. auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
  278. check(EC, Path);
  279. return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
  280. };
  281. auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
  282. *AddStream(Task)->OS << MB->getBuffer();
  283. };
  284. NativeObjectCache Cache;
  285. if (!CacheDir.empty())
  286. Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
  287. check(Lto.run(AddStream, Cache), "LTO::run failed");
  288. return 0;
  289. }
  290. static int dumpSymtab(int argc, char **argv) {
  291. for (StringRef F : make_range(argv + 1, argv + argc)) {
  292. std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
  293. BitcodeFileContents BFC = check(getBitcodeFileContents(*MB), F);
  294. if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
  295. auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
  296. BFC.Symtab.data());
  297. outs() << "version: " << Hdr->Version << '\n';
  298. if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
  299. outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab)
  300. << '\n';
  301. }
  302. std::unique_ptr<InputFile> Input =
  303. check(InputFile::create(MB->getMemBufferRef()), F);
  304. outs() << "target triple: " << Input->getTargetTriple() << '\n';
  305. Triple TT(Input->getTargetTriple());
  306. outs() << "source filename: " << Input->getSourceFileName() << '\n';
  307. if (TT.isOSBinFormatCOFF())
  308. outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
  309. if (TT.isOSBinFormatELF()) {
  310. outs() << "dependent libraries:";
  311. for (auto L : Input->getDependentLibraries())
  312. outs() << " \"" << L << "\"";
  313. outs() << '\n';
  314. }
  315. std::vector<StringRef> ComdatTable = Input->getComdatTable();
  316. for (const InputFile::Symbol &Sym : Input->symbols()) {
  317. switch (Sym.getVisibility()) {
  318. case GlobalValue::HiddenVisibility:
  319. outs() << 'H';
  320. break;
  321. case GlobalValue::ProtectedVisibility:
  322. outs() << 'P';
  323. break;
  324. case GlobalValue::DefaultVisibility:
  325. outs() << 'D';
  326. break;
  327. }
  328. auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
  329. PrintBool('U', Sym.isUndefined());
  330. PrintBool('C', Sym.isCommon());
  331. PrintBool('W', Sym.isWeak());
  332. PrintBool('I', Sym.isIndirect());
  333. PrintBool('O', Sym.canBeOmittedFromSymbolTable());
  334. PrintBool('T', Sym.isTLS());
  335. PrintBool('X', Sym.isExecutable());
  336. outs() << ' ' << Sym.getName() << '\n';
  337. if (Sym.isCommon())
  338. outs() << " size " << Sym.getCommonSize() << " align "
  339. << Sym.getCommonAlignment() << '\n';
  340. int Comdat = Sym.getComdatIndex();
  341. if (Comdat != -1)
  342. outs() << " comdat " << ComdatTable[Comdat] << '\n';
  343. if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
  344. outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
  345. if (!Sym.getSectionName().empty())
  346. outs() << " section " << Sym.getSectionName() << "\n";
  347. }
  348. outs() << '\n';
  349. }
  350. return 0;
  351. }
  352. int main(int argc, char **argv) {
  353. InitLLVM X(argc, argv);
  354. InitializeAllTargets();
  355. InitializeAllTargetMCs();
  356. InitializeAllAsmPrinters();
  357. InitializeAllAsmParsers();
  358. // FIXME: This should use llvm::cl subcommands, but it isn't currently
  359. // possible to pass an argument not associated with a subcommand to a
  360. // subcommand (e.g. -use-new-pm).
  361. if (argc < 2)
  362. return usage();
  363. StringRef Subcommand = argv[1];
  364. // Ensure that argv[0] is correct after adjusting argv/argc.
  365. argv[1] = argv[0];
  366. if (Subcommand == "dump-symtab")
  367. return dumpSymtab(argc - 1, argv + 1);
  368. if (Subcommand == "run")
  369. return run(argc - 1, argv + 1);
  370. return usage();
  371. }